「题解」Codeforces 825G Tree Queries

· · 题解

点权转边权,把边权设为两个端点的 \min,然后发现询问 x 的答案,就是询问 x 与所有黑点的虚树,边权的 \min 是多少。假设要判定答案是否 \geq k,那么就是询问 x 只经过 \geq k 是否能到达所有黑点,于是想到建立 Kruskal 重构树,那么 x 与所有黑点的 LCA 的权值即为答案。时间复杂度为 \mathcal{O}(n+q\log n)

#include<cstdio>
#include<vector>
#include<queue>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<ctime>
#include<random>
#include<assert.h>
#define pb emplace_back
#define mp make_pair
#define fi first
#define se second
#define dbg(x) cerr<<"In Line "<< __LINE__<<" the "<<#x<<" = "<<x<<'\n'
#define dpi(x,y) cerr<<"In Line "<<__LINE__<<" the "<<#x<<" = "<<x<<" ; "<<"the "<<#y<<" = "<<y<<'\n'
#define DE(fmt,...) fprintf(stderr, "Line %d : " fmt "\n",__LINE__,##__VA_ARGS__)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int>pii;
typedef pair<ll,int>pli;
typedef pair<ll,ll>pll;
typedef pair<int,ll>pil;
typedef vector<int>vi;
typedef vector<ll>vll;
typedef vector<pii>vpii;
typedef vector<pll>vpll;
template<typename T>T cmax(T &x, T y){return x=x>y?x:y;}
template<typename T>T cmin(T &x, T y){return x=x<y?x:y;}
template<typename T>
T &read(T &r){
    r=0;bool w=0;char ch=getchar();
    while(ch<'0'||ch>'9')w=ch=='-'?1:0,ch=getchar();
    while(ch>='0'&&ch<='9')r=r*10+(ch^48),ch=getchar();
    return r=w?-r:r;
}
template<typename T1,typename... T2>
void read(T1 &x,T2& ...y){read(x);read(y...);}
const int N=2000010;
int n,m;
struct Edge{
    int x,y,w;
}e[N];
vi eg[N];
int tot,val[N],fa[N];
int getfa(int x){return fa[x]==x?x:fa[x]=getfa(fa[x]);}
int dep[N],top[N],pa[N],son[N],siz[N];
void dfs1(int x){
    siz[x]=1;
    for(auto v:eg[x]){
        dep[v]=dep[x]+1;pa[v]=x;
        dfs1(v);siz[x]+=siz[v];
        if(siz[v]>siz[son[x]])son[x]=v;
    }
}
void dfs2(int x,int t){
    top[x]=t;
    if(son[x])dfs2(son[x],t);
    for(auto v:eg[x])if(v!=son[x])dfs2(v,v);
}
int LCA(int x,int y){
    while(top[x]!=top[y]){
        if(dep[top[x]]<dep[top[y]])swap(x,y);
        x=pa[top[x]];
    }
    return dep[x]<dep[y]?x:y;
}
signed main(){
    #ifdef do_while_true
//      assert(freopen("data.in","r",stdin));
//      assert(freopen("data.out","w",stdout));
    #endif
    read(n,m);
    for(int i=1;i<n;i++)read(e[i].x,e[i].y),e[i].w=min(e[i].x,e[i].y);
    sort(e+1,e+n,[&](const Edge &x,const Edge &y){return x.w>y.w;});
    tot=n;
    for(int i=1;i<=n;i++)fa[i]=val[i]=i;
    for(int i=1;i<n;i++){
        int x=e[i].x,y=e[i].y,w=e[i].w;
        x=getfa(x);y=getfa(y);
        ++tot;val[tot]=w;
        eg[tot].pb(x);eg[tot].pb(y);
        fa[x]=fa[y]=fa[tot]=tot;
    }
    dfs1(tot);
    dfs2(tot,tot);
    int las=0,t=0;
    while(m--){
        int op,x;read(op,x);
        x=(las+x)%n+1;
        if(op==1){
            if(!t)t=x;
            else t=LCA(t,x);
        }
        else{
            las=val[LCA(t,x)];
            cout<<las<<'\n';
        }
    }
    #ifdef do_while_true
//      cerr<<'\n'<<"Time:"<<1.0*clock()/CLOCKS_PER_SEC*1000<<" ms"<<'\n';
    #endif
    return 0;
}