跳到正文

题解

遇到弱智了

NewMarchqwq约 58 分钟
原文
文章信息与版本

文章信息

发布
2026年10月31日
收录
2026年10月31日
更新
2026年11月10日
篇幅
约 58 分钟
题目
P17834

版本

  1. v1当前

CSP-S2026 T4 题解。这是一个比较复杂的做法;贴的所有代码都是 gpt 的。

Θ(n2log⁡n)\Theta(n^2\log n)

显然先二分答案 XX,不然做个锤锤。

考察这个题目最难以限制的是需要至多两个连通块。但是我们发现一件事情就是我们可以钦定某一条边的两个端点分别受两个连通块贡献。如果我们钦定错了,那么答案只可能更不优,因为原本不是他管的他得跑过来管;但是钦定对了就得到了答案。因此相当于我们可以把这条边断掉,问题转化为了对于两个剩下的新树做单个连通块的问题。

对于 Θ(n2log⁡n)\Theta(n^2\log n),我们剩下的按照自己喜欢的方式线性处理单条边的情况即可。

code
C++
// User-route implementation: see user_route_proof.md for precise definitions.
#include <bits/stdc++.h>
using namespace std;
const int NEG = -1000000007;
struct FastInput {
    static const int S=1<<20; char b[S]; int p=0,len=0;
    int get(){if(p==len){len=fread(b,1,S,stdin);p=0;if(!len)return EOF;}return b[p++];}
    bool read(int &x){int c;do{c=get();if(c==EOF)return false;}while(c<=32);x=0;do{x=x*10+c-'0';c=get();}while(c>='0'&&c<='9');return true;}
};
struct Tree {
    int n,ec=0; vector<int>head,to,nxt;
    Tree(int n):n(n),head(n+1,-1),to(2*n-2),nxt(2*n-2){}
    void add(int u,int v){to[ec]=v;nxt[ec]=head[u];head[u]=ec++;to[ec]=u;nxt[ec]=head[v];head[v]=ec++;}
};
struct Rooted {
    const Tree &tr;int root;
    vector<int>p,dep,ord,h,leaf,sz,heavy,first,second,third,c1,c2,c3,up,upLeaf;
    Rooted(const Tree &t):tr(t),p(t.n+1),dep(t.n+1),h(t.n+1),leaf(t.n+1),sz(t.n+1),heavy(t.n+1),first(t.n+1),second(t.n+1),third(t.n+1),c1(t.n+1),c2(t.n+1),c3(t.n+1),up(t.n+1),upLeaf(t.n+1){ord.reserve(t.n);}
    void build(int r,bool needUp=false){
        root=r;ord.clear();ord.push_back(r);p[r]=0;dep[r]=0;
        // This is a parent-before-child order; later reverse it for tree DP.
        for(size_t i=0;i<ord.size();++i){int u=ord[i];for(int e=tr.head[u];e!=-1;e=tr.nxt[e]){int v=tr.to[e];if(v==p[u])continue;p[v]=u;dep[v]=dep[u]+1;ord.push_back(v);}}
        for(int i=tr.n-1;i>=0;--i){
            int u=ord[i];h[u]=first[u]=second[u]=third[u]=0;leaf[u]=u;sz[u]=1;heavy[u]=c1[u]=c2[u]=c3[u]=0;
            for(int e=tr.head[u];e!=-1;e=tr.nxt[e]){int v=tr.to[e];if(p[v]!=u)continue;
                sz[u]+=sz[v];if(!heavy[u]||sz[v]>sz[heavy[u]])heavy[u]=v;
                int d=h[v]+1;
                if(d>first[u]){third[u]=second[u];c3[u]=c2[u];second[u]=first[u];c2[u]=c1[u];first[u]=d;c1[u]=v;}
                else if(d>second[u]){third[u]=second[u];c3[u]=c2[u];second[u]=d;c2[u]=v;}
                else if(d>third[u]){third[u]=d;c3[u]=v;}
            }
            h[u]=first[u];if(c1[u])leaf[u]=leaf[c1[u]];
        }
        if(needUp){up[r]=0;upLeaf[r]=r;for(int u:ord)for(int e=tr.head[u];e!=-1;e=tr.nxt[e]){int v=tr.to[e];if(p[v]!=u)continue;
            int sibling=c1[u]==v?second[u]:first[u],who=c1[u]==v?c2[u]:c1[u];
            if(up[u]>=sibling)up[v]=up[u]+1,upLeaf[v]=upLeaf[u];
            else up[v]=sibling+1,upLeaf[v]=who?leaf[who]:u;
        }}
    }
    int side(int u,int child)const{return c1[u]==child?second[u]:first[u];}
    int excludingTwo(int u,int a,int b)const{
        if(c1[u]!=a&&c1[u]!=b)return first[u];
        if(c2[u]!=a&&c2[u]!=b)return second[u];
        return third[u];
    }
};
struct MaxSeg {
    int n,s=1;vector<int>a,b;
    MaxSeg(int n):n(n){while(s<n)s<<=1;a.assign(2*s,NEG);b.assign(2*s,NEG);}
    void set(int x,int v,int w){int q=x+s;a[q]=v;b[q]=w;while(q>>=1)a[q]=max(a[q*2],a[q*2+1]),b[q]=max(b[q*2],b[q*2+1]);}
    void build(const vector<int>&v,const vector<int>&w){fill(a.begin(),a.end(),NEG);fill(b.begin(),b.end(),NEG);for(int i=0;i<n;i++)a[s+i]=v[i],b[s+i]=w[i];for(int q=s-1;q;q--)a[q]=max(a[q*2],a[q*2+1]),b[q]=max(b[q*2],b[q*2+1]);}
    int maximum(int l,int r,int type)const{const auto &z=type?b:a;int ans=NEG;for(l+=s,r+=s+1;l<r;l>>=1,r>>=1){if(l&1)ans=max(ans,z[l++]);if(r&1)ans=max(ans,z[--r]);}return ans;}
    int locate(int q,int l,int r,int ql,int qr,int threshold,int type,bool right)const{
        const auto &z=type?b:a;if(r<ql||qr<l||z[q]<threshold)return -1;if(l==r)return l;
        int m=(l+r)/2,t;
        if(right){t=locate(q*2+1,m+1,r,ql,qr,threshold,type,right);if(t!=-1)return t;return locate(q*2,l,m,ql,qr,threshold,type,right);}
        t=locate(q*2,l,m,ql,qr,threshold,type,right);if(t!=-1)return t;return locate(q*2+1,m+1,r,ql,qr,threshold,type,right);
    }
    int find(int l,int r,int t,int type,bool right)const{return l>r?-1:locate(1,0,s-1,l,r,t,type,right);}
};

// Original route: enumerate a cut, then count mandatory vertices in each component.
struct Solver {
    const Tree &tr;vector<int>p,ord,h,second,up,component;int n;
    Solver(const Tree&t):tr(t),p(t.n+1),h(t.n+1),second(t.n+1),up(t.n+1),component(t.n+1),n(t.n){ord.reserve(n);}
    int count(int R,int blocked){
        ord.clear();int roots=blocked<0?1:2;
        if(blocked<0){ord.push_back(1);p[1]=0;component[1]=0;}
        else for(int j=0;j<2;j++){int u=tr.to[2*blocked+j];ord.push_back(u);p[u]=0;component[u]=j;}
        for(size_t i=0;i<ord.size();i++){int u=ord[i];for(int e=tr.head[u];e!=-1;e=tr.nxt[e]){if((e>>1)==blocked)continue;int v=tr.to[e];if(v==p[u])continue;p[v]=u;component[v]=component[u];ord.push_back(v);}}
        for(int i=n-1;i>=0;i--){int u=ord[i];h[u]=second[u]=0;for(int e=tr.head[u];e!=-1;e=tr.nxt[e]){if((e>>1)==blocked)continue;int v=tr.to[e];if(p[v]!=u)continue;int d=h[v]+1;if(d>h[u])second[u]=h[u],h[u]=d;else second[u]=max(second[u],d);}}
        int ans[2]={0,0};for(int i=0;i<roots;i++)up[ord[i]]=0;
        for(int u:ord){int large=(up[u]>=R);for(int e=tr.head[u];e!=-1;e=tr.nxt[e]){if((e>>1)==blocked)continue;int v=tr.to[e];if(p[v]!=u)continue;large+=h[v]+1>=R;int other=h[v]+1==h[u]?second[u]:h[u];up[v]=max(up[u],other)+1;}ans[component[u]]+=large>=2;}
        return max(1,ans[0])+(roots==2?max(1,ans[1]):0);
    }
    int minimum(int R){if(!R)return n;int best=count(R,-1);if(best<=2)return best;for(int e=0;e<n-1;e++){best=min(best,count(R,e));if(best==2)break;}return best;}
};

int main(){
#ifndef LOCAL
    freopen("hub.in","r",stdin);freopen("hub.out","w",stdout);
#endif
    static FastInput in;int c,t;if(!in.read(c))return 0;in.read(t);
    while(t--){int n,k;in.read(n);in.read(k);Tree tr(n);for(int i=1;i<n;i++){int u,v;in.read(u);in.read(v);tr.add(u,v);}if(k==n){puts("0");continue;}Solver solver(tr);int l=1,r=n/2;while(l<r){int m=(l+r)/2;if(solver.minimum(m)<=k)r=m;else l=m+1;}printf("%d\n",l);}
}

Θ(nlog⁡3n)\Theta(n\log^3n)

赛时只想到这个。难道我真的是弱智??

考察怎么做单个连通块。什么样的点是必须选取的呢?

  • Lemma. 当且仅当它有至少两个子树(包括连向父亲的那个)的深度 ≥X\ge X 时它是必须选的点。

证明:满足这个不选的话那个子树里就得选,那么两个子树都选就不是一个连通块了;不满足这个选的话删掉一定没问题,不如删掉。

我们考察断掉边 (f=fau,u)(f=fa_u,u) 之后,子树内的情况很好处理;子树外的情况,我们考察一个点 xx 的现在的答案。下面进行分类讨论。我们如果记不包括父亲,其他子树的最深深度的可重集合为 SS,那么:

  • 对于 xx 是 ff 祖先,我们需要 S−{lenv}+{val(x,u),up(x,x)}S-\{len_v\}+\{val(x,u),up(x,x)\} 中有至少两个 ≥X\ge X 的数;
  • 否则我们需要 S+{max⁡(up(x,lca(x,f)),val(x,u))}S+\{\max(up(x,lca(x,f)),val(x,u))\} 中有至少两个 ≥X\ge X 的数。

上面 up(x,t)up(x,t) 的意思是 xx 向上走到一个 tt 以上祖先再往下的最长链;vv 是 xx 的儿子且其子树内包含 ff;val(x,u)val(x,u) 指的是 xx 走到 lca(x,f)lca(x,f) 然后往下不碰 uu 拐走的最长链,也就是 dis(x,lca(x,f))dis(x,lca(x,f)) 加上 lca(x,f)lca(x,f) 的除去 ff 相关后另一条长链长度。

看着好像这个 up 和 val 都不好维护,实际上可以拆成类似 max⁡(len(lca(x,f)),up(lca(x,f)))+dep(x)−dep(lca(x,f))\max(len(lca(x,f)),up(lca(x,f)))+dep(x)-dep(lca(x,f)) 的形式(当它在最长链上会有些许不同),因此只需要研究这个 lca 的位置,需要树剖线段树来维护(类比点分树模板题的树剖线段树做法),2log。

最后带上二分就是 Θ(nlog⁡3n)\Theta(n\log^3n) 的复杂度。

code
C++
// User-route implementation: see user_route_proof.md for precise definitions.
#include <bits/stdc++.h>
using namespace std;
const int NEG = -1000000007;
struct FastInput {
    static const int S=1<<20; char b[S]; int p=0,len=0;
    int get(){if(p==len){len=fread(b,1,S,stdin);p=0;if(!len)return EOF;}return b[p++];}
    bool read(int &x){int c;do{c=get();if(c==EOF)return false;}while(c<=32);x=0;do{x=x*10+c-'0';c=get();}while(c>='0'&&c<='9');return true;}
};
struct Tree {
    int n,ec=0; vector<int>head,to,nxt;
    Tree(int n):n(n),head(n+1,-1),to(2*n-2),nxt(2*n-2){}
    void add(int u,int v){to[ec]=v;nxt[ec]=head[u];head[u]=ec++;to[ec]=u;nxt[ec]=head[v];head[v]=ec++;}
};
struct Rooted {
    const Tree &tr;int root;
    vector<int>p,dep,ord,h,leaf,sz,heavy,first,second,third,c1,c2,c3,up,upLeaf;
    Rooted(const Tree &t):tr(t),p(t.n+1),dep(t.n+1),h(t.n+1),leaf(t.n+1),sz(t.n+1),heavy(t.n+1),first(t.n+1),second(t.n+1),third(t.n+1),c1(t.n+1),c2(t.n+1),c3(t.n+1),up(t.n+1),upLeaf(t.n+1){ord.reserve(t.n);}
    void build(int r,bool needUp=false){
        root=r;ord.clear();ord.push_back(r);p[r]=0;dep[r]=0;
        // This is a parent-before-child order; later reverse it for tree DP.
        for(size_t i=0;i<ord.size();++i){int u=ord[i];for(int e=tr.head[u];e!=-1;e=tr.nxt[e]){int v=tr.to[e];if(v==p[u])continue;p[v]=u;dep[v]=dep[u]+1;ord.push_back(v);}}
        for(int i=tr.n-1;i>=0;--i){
            int u=ord[i];h[u]=first[u]=second[u]=third[u]=0;leaf[u]=u;sz[u]=1;heavy[u]=c1[u]=c2[u]=c3[u]=0;
            for(int e=tr.head[u];e!=-1;e=tr.nxt[e]){int v=tr.to[e];if(p[v]!=u)continue;
                sz[u]+=sz[v];if(!heavy[u]||sz[v]>sz[heavy[u]])heavy[u]=v;
                int d=h[v]+1;
                if(d>first[u]){third[u]=second[u];c3[u]=c2[u];second[u]=first[u];c2[u]=c1[u];first[u]=d;c1[u]=v;}
                else if(d>second[u]){third[u]=second[u];c3[u]=c2[u];second[u]=d;c2[u]=v;}
                else if(d>third[u]){third[u]=d;c3[u]=v;}
            }
            h[u]=first[u];if(c1[u])leaf[u]=leaf[c1[u]];
        }
        if(needUp){up[r]=0;upLeaf[r]=r;for(int u:ord)for(int e=tr.head[u];e!=-1;e=tr.nxt[e]){int v=tr.to[e];if(p[v]!=u)continue;
            int sibling=c1[u]==v?second[u]:first[u],who=c1[u]==v?c2[u]:c1[u];
            if(up[u]>=sibling)up[v]=up[u]+1,upLeaf[v]=upLeaf[u];
            else up[v]=sibling+1,upLeaf[v]=who?leaf[who]:u;
        }}
    }
    int side(int u,int child)const{return c1[u]==child?second[u]:first[u];}
    int excludingTwo(int u,int a,int b)const{
        if(c1[u]!=a&&c1[u]!=b)return first[u];
        if(c2[u]!=a&&c2[u]!=b)return second[u];
        return third[u];
    }
};
struct MaxSeg {
    int n,s=1;vector<int>a,b;
    MaxSeg(int n):n(n){while(s<n)s<<=1;a.assign(2*s,NEG);b.assign(2*s,NEG);}
    void set(int x,int v,int w){int q=x+s;a[q]=v;b[q]=w;while(q>>=1)a[q]=max(a[q*2],a[q*2+1]),b[q]=max(b[q*2],b[q*2+1]);}
    void build(const vector<int>&v,const vector<int>&w){fill(a.begin(),a.end(),NEG);fill(b.begin(),b.end(),NEG);for(int i=0;i<n;i++)a[s+i]=v[i],b[s+i]=w[i];for(int q=s-1;q;q--)a[q]=max(a[q*2],a[q*2+1]),b[q]=max(b[q*2],b[q*2+1]);}
    int maximum(int l,int r,int type)const{const auto &z=type?b:a;int ans=NEG;for(l+=s,r+=s+1;l<r;l>>=1,r>>=1){if(l&1)ans=max(ans,z[l++]);if(r&1)ans=max(ans,z[--r]);}return ans;}
    int locate(int q,int l,int r,int ql,int qr,int threshold,int type,bool right)const{
        const auto &z=type?b:a;if(r<ql||qr<l||z[q]<threshold)return -1;if(l==r)return l;
        int m=(l+r)/2,t;
        if(right){t=locate(q*2+1,m+1,r,ql,qr,threshold,type,right);if(t!=-1)return t;return locate(q*2,l,m,ql,qr,threshold,type,right);}
        t=locate(q*2,l,m,ql,qr,threshold,type,right);if(t!=-1)return t;return locate(q*2+1,m+1,r,ql,qr,threshold,type,right);
    }
    int find(int l,int r,int t,int type,bool right)const{return l>r?-1:locate(1,0,s-1,l,r,t,type,right);}
};

struct HLD {
    Rooted &d;vector<int>top,pos,rev;MaxSeg seg;
    HLD(Rooted&d):d(d),top(d.tr.n+1),pos(d.tr.n+1),rev(d.tr.n),seg(d.tr.n){
        int timer=0;vector<pair<int,int>>st{{d.root,d.root}};
        while(!st.empty()){auto [u,t]=st.back();st.pop_back();for(;u;u=d.heavy[u]){top[u]=t;pos[u]=timer;rev[timer++]=u;for(int e=d.tr.head[u];e!=-1;e=d.tr.nxt[e]){int v=d.tr.to[e];if(d.p[v]==u&&v!=d.heavy[u])st.push_back({v,v});}}}
        vector<int>a(d.tr.n,NEG),b(d.tr.n,NEG);for(int v=1;v<=d.tr.n;v++)if(d.p[v]){int u=d.p[v],h=d.side(u,v);a[pos[v]]=h-d.dep[u];b[pos[v]]=h+d.dep[u];}seg.build(a,b);
    }
    int lca(int u,int v)const{while(top[u]!=top[v]){if(d.dep[top[u]]<d.dep[top[v]])swap(u,v);u=d.p[top[u]];}return d.dep[u]<d.dep[v]?u:v;}
    int ancestor(int u,int steps)const{while(steps>d.dep[u]-d.dep[top[u]])steps-=d.dep[u]-d.dep[top[u]]+1,u=d.p[top[u]];return rev[pos[u]-steps];}
    int kth(int x,int w,int steps)const{int t=lca(x,w),left=d.dep[x]-d.dep[t];if(steps<=left)return ancestor(x,steps);int total=left+d.dep[w]-d.dep[t];return ancestor(w,total-steps);}
    int firstUp(int v,int minimumDepth,int threshold)const{
        while(v&&d.dep[v]>=minimumDepth){int t=top[v],lo=pos[t]+max(0,minimumDepth-d.dep[t]);int ans=seg.find(lo,pos[v],threshold,0,true);if(ans!=-1)return rev[ans];v=d.p[t];}return 0;
    }
    int firstDown(int v,int minimumDepth,int threshold)const{
        vector<pair<int,int>>ranges;
        while(v&&d.dep[v]>=minimumDepth){int t=top[v],lo=pos[t]+max(0,minimumDepth-d.dep[t]);ranges.push_back({lo,pos[v]});v=d.p[t];}
        for(int i=(int)ranges.size()-1;i>=0;i--){auto [l,r]=ranges[i];int ans=seg.find(l,r,threshold,1,false);if(ans!=-1)return rev[ans];}return 0;
    }
    // Common prefix of paths to all vertices at distance >= R in the chosen direction.
    int critical(int x,int w,int R)const{
        int t=lca(x,w),left=d.dep[x]-d.dep[t];
        int z=firstUp(x,d.dep[t]+2,R-d.dep[x]);
        if(z){int b=d.p[z];if(d.dep[x]-d.dep[b]<R)return b;}
        if(R<=left)return ancestor(x,R);
        if(t!=x){
            int a=ancestor(x,left-1),b=ancestor(w,d.dep[w]-d.dep[t]-1);
            int off=max(d.up[t],d.excludingTwo(t,a,b));
            if(left+off>=R)return t;
        }
        z=firstDown(w,d.dep[t]+2,R-d.dep[x]+2*d.dep[t]);
        if(z){int b=d.p[z];if(left+d.dep[b]-d.dep[t]<R)return b;}
        return kth(x,w,R);
    }
};
struct Solver {
    const Tree &tr;Rooted d;unique_ptr<HLD> hld;
    vector<int>globalSub,lossIn,lossOut;
    Solver(const Tree&t):tr(t),d(t),globalSub(t.n+1),lossIn(t.n+1),lossOut(t.n+1){d.build(1,true);hld=make_unique<HLD>(d);}
    int minimum(int R){
        if(!R)return tr.n;
        fill(globalSub.begin(),globalSub.end(),0);fill(lossIn.begin(),lossIn.end(),0);fill(lossOut.begin(),lossOut.end(),0);
        int total=0;
        for(int x:d.ord){
            int count=d.up[x]>=R;
            for(int e=tr.head[x];e!=-1;e=tr.nxt[e]){int v=tr.to[e];if(d.p[v]==x)count+=d.h[v]+1>=R;}
            if(count>=2)globalSub[x]=1,++total;
            if(count!=2)continue;
            auto addDirection=[&](int w){int b=hld->critical(x,w,R),a=hld->lca(x,b);++lossIn[x];--lossIn[a];++lossOut[b];--lossOut[a];};
            if(d.up[x]>=R)addDirection(d.upLeaf[x]);
            for(int e=tr.head[x];e!=-1;e=tr.nxt[e]){int v=tr.to[e];if(d.p[v]==x&&d.h[v]+1>=R)addDirection(d.leaf[v]);}
        }
        if(total<=2)return max(1,total);
        for(int i=tr.n-1;i>0;i--){int u=d.ord[i],p=d.p[u];globalSub[p]+=globalSub[u];lossIn[p]+=lossIn[u];lossOut[p]+=lossOut[u];}
        int best=total;
        for(int u=2;u<=tr.n;u++){
            int a=globalSub[u]-lossIn[u],b=total-globalSub[u]-lossOut[u];
            best=min(best,max(1,a)+max(1,b));
        }
        return best;
    }
};

int main(){
#ifndef LOCAL
    freopen("hub.in","r",stdin);freopen("hub.out","w",stdout);
#endif
    static FastInput in;int c,t;if(!in.read(c))return 0;in.read(t);
    while(t--){int n,k;in.read(n);in.read(k);Tree tr(n);for(int i=1;i<n;i++){int u,v;in.read(u);in.read(v);tr.add(u,v);}if(k==n){puts("0");continue;}Solver solver(tr);int l=1,r=n/2;while(l<r){int m=(l+r)/2;if(solver.minimum(m)<=k)r=m;else l=m+1;}printf("%d\n",l);}
}
```cpp

Θ(nlog⁡2n)\Theta(n\log^2n)

饭堂了。

注意到一个事实就是我们是必须选一个最深的叶子的恰好 XX 级祖先的,无论你怎么定根。证明是,往低了选没有意义。

因此我们把它定为根,做之前的东西。我们发现了什么:现在上面那一半变成了,只要子树内有一个 ≥X\ge X 的到这个点的链,我就必须选了!因为我们必须选根。然后我们现在不需要管子树外的情况了,而且次数也从 22 变成了 11。

这带来了什么:首先上面如果 xx 不是 ff 的祖先,那么它的贡献事先确定了,可以线性预处理;而祖先的贡献相当于分成两种,一种祖先是直接加;另一种是需要你到了一定深度才能加,就是当你 ff 去掉 uu 子树内最长链 ≥X+dep(x)−dep(f)\ge X+dep(x)-dep(f) 的时候才能加。

用线段树维护,可以做到 Θ(nlog⁡2n)\Theta(n\log^2n)。

code
C++
// User-route implementation: see user_route_proof.md for precise definitions.
#include <bits/stdc++.h>
using namespace std;
const int NEG = -1000000007;
struct FastInput {
    static const int S=1<<20; char b[S]; int p=0,len=0;
    int get(){if(p==len){len=fread(b,1,S,stdin);p=0;if(!len)return EOF;}return b[p++];}
    bool read(int &x){int c;do{c=get();if(c==EOF)return false;}while(c<=32);x=0;do{x=x*10+c-'0';c=get();}while(c>='0'&&c<='9');return true;}
};
struct Tree {
    int n,ec=0; vector<int>head,to,nxt;
    Tree(int n):n(n),head(n+1,-1),to(2*n-2),nxt(2*n-2){}
    void add(int u,int v){to[ec]=v;nxt[ec]=head[u];head[u]=ec++;to[ec]=u;nxt[ec]=head[v];head[v]=ec++;}
};
struct Rooted {
    const Tree &tr;int root;
    vector<int>p,dep,ord,h,leaf,sz,heavy,first,second,third,c1,c2,c3,up,upLeaf;
    Rooted(const Tree &t):tr(t),p(t.n+1),dep(t.n+1),h(t.n+1),leaf(t.n+1),sz(t.n+1),heavy(t.n+1),first(t.n+1),second(t.n+1),third(t.n+1),c1(t.n+1),c2(t.n+1),c3(t.n+1),up(t.n+1),upLeaf(t.n+1){ord.reserve(t.n);}
    void build(int r,bool needUp=false){
        root=r;ord.clear();ord.push_back(r);p[r]=0;dep[r]=0;
        // This is a parent-before-child order; later reverse it for tree DP.
        for(size_t i=0;i<ord.size();++i){int u=ord[i];for(int e=tr.head[u];e!=-1;e=tr.nxt[e]){int v=tr.to[e];if(v==p[u])continue;p[v]=u;dep[v]=dep[u]+1;ord.push_back(v);}}
        for(int i=tr.n-1;i>=0;--i){
            int u=ord[i];h[u]=first[u]=second[u]=third[u]=0;leaf[u]=u;sz[u]=1;heavy[u]=c1[u]=c2[u]=c3[u]=0;
            for(int e=tr.head[u];e!=-1;e=tr.nxt[e]){int v=tr.to[e];if(p[v]!=u)continue;
                sz[u]+=sz[v];if(!heavy[u]||sz[v]>sz[heavy[u]])heavy[u]=v;
                int d=h[v]+1;
                if(d>first[u]){third[u]=second[u];c3[u]=c2[u];second[u]=first[u];c2[u]=c1[u];first[u]=d;c1[u]=v;}
                else if(d>second[u]){third[u]=second[u];c3[u]=c2[u];second[u]=d;c2[u]=v;}
                else if(d>third[u]){third[u]=d;c3[u]=v;}
            }
            h[u]=first[u];if(c1[u])leaf[u]=leaf[c1[u]];
        }
        if(needUp){up[r]=0;upLeaf[r]=r;for(int u:ord)for(int e=tr.head[u];e!=-1;e=tr.nxt[e]){int v=tr.to[e];if(p[v]!=u)continue;
            int sibling=c1[u]==v?second[u]:first[u],who=c1[u]==v?c2[u]:c1[u];
            if(up[u]>=sibling)up[v]=up[u]+1,upLeaf[v]=upLeaf[u];
            else up[v]=sibling+1,upLeaf[v]=who?leaf[who]:u;
        }}
    }
    int side(int u,int child)const{return c1[u]==child?second[u]:first[u];}
    int excludingTwo(int u,int a,int b)const{
        if(c1[u]!=a&&c1[u]!=b)return first[u];
        if(c2[u]!=a&&c2[u]!=b)return second[u];
        return third[u];
    }
};
struct MaxSeg {
    int n,s=1;vector<int>a,b;
    MaxSeg(int n):n(n){while(s<n)s<<=1;a.assign(2*s,NEG);b.assign(2*s,NEG);}
    void set(int x,int v,int w){int q=x+s;a[q]=v;b[q]=w;while(q>>=1)a[q]=max(a[q*2],a[q*2+1]),b[q]=max(b[q*2],b[q*2+1]);}
    void build(const vector<int>&v,const vector<int>&w){fill(a.begin(),a.end(),NEG);fill(b.begin(),b.end(),NEG);for(int i=0;i<n;i++)a[s+i]=v[i],b[s+i]=w[i];for(int q=s-1;q;q--)a[q]=max(a[q*2],a[q*2+1]),b[q]=max(b[q*2],b[q*2+1]);}
    int maximum(int l,int r,int type)const{const auto &z=type?b:a;int ans=NEG;for(l+=s,r+=s+1;l<r;l>>=1,r>>=1){if(l&1)ans=max(ans,z[l++]);if(r&1)ans=max(ans,z[--r]);}return ans;}
    int locate(int q,int l,int r,int ql,int qr,int threshold,int type,bool right)const{
        const auto &z=type?b:a;if(r<ql||qr<l||z[q]<threshold)return -1;if(l==r)return l;
        int m=(l+r)/2,t;
        if(right){t=locate(q*2+1,m+1,r,ql,qr,threshold,type,right);if(t!=-1)return t;return locate(q*2,l,m,ql,qr,threshold,type,right);}
        t=locate(q*2,l,m,ql,qr,threshold,type,right);if(t!=-1)return t;return locate(q*2+1,m+1,r,ql,qr,threshold,type,right);
    }
    int find(int l,int r,int t,int type,bool right)const{return l>r?-1:locate(1,0,s-1,l,r,t,type,right);}
};

// The anchor is the R-th ancestor of a deepest leaf in the original rooting.
struct AnchorBase {
    const Tree &tr;Rooted d;vector<int>deepPath,activeSub,prefix;
    AnchorBase(const Tree&t):tr(t),d(t),activeSub(t.n+1),prefix(t.n+1){
        d.build(1);int leaf=d.leaf[1];while(leaf)deepPath.push_back(leaf),leaf=d.p[leaf];
        // deepPath[R] is precisely the required R-th ancestor.
    }
    bool prepare(int R){
        if(R>=(int)deepPath.size()-1)return false;
        d.build(deepPath[R]);
        for(int u:d.ord){int flag=u==d.root||d.h[u]>=R;activeSub[u]=flag;prefix[u]=(d.p[u]?prefix[d.p[u]]:0)+flag;}
        for(int i=tr.n-1;i>0;i--){int u=d.ord[i];activeSub[d.p[u]]+=activeSub[u];}
        return true;
    }
};

struct Solver:AnchorBase {
    MaxSeg seg;vector<int>inside,path;
    Solver(const Tree&t):AnchorBase(t),seg(t.n),inside(t.n+1),path(t.n){}
    int minimum(int R){
        if(!R)return tr.n;if(!prepare(R))return 1;
        fill(inside.begin(),inside.end(),0);
        // Preorder makes a depth-indexed segment tree represent the current path.
        // Rooted::ord is parent-before-child but is BFS-like; use an explicit DFS.
        vector<int>stack(1,d.root);
        int best=activeSub[d.root];
        vector<int>outside(tr.n+1);
        while(!stack.empty()){
            int u=stack.back();stack.pop_back();path[d.dep[u]]=u;
            if(d.p[u]){
                int p=d.p[u],s=d.side(p,u),key=min(d.dep[p],d.dep[p]+s-R);
                seg.set(d.dep[p],s-d.dep[p],key);
                int D=seg.maximum(0,d.dep[u]-1,1);
                outside[u]=activeSub[d.root]-activeSub[u]-prefix[p]+max(1,D+1);
            }
            if(d.second[u]>=R)++inside[u];
            else if(d.first[u]>=R&&d.p[u]){
                int a=seg.find(0,d.dep[u]-1,R-d.dep[u],0,true);
                if(a!=-1)++inside[path[a]];
            }
            for(int e=tr.head[u];e!=-1;e=tr.nxt[e]){int v=tr.to[e];if(d.p[v]==u)stack.push_back(v);}
        }
        for(int i=tr.n-1;i>0;i--){int u=d.ord[i];inside[d.p[u]]+=inside[u];}
        for(int u:d.ord)if(d.p[u])best=min(best,outside[u]+max(1,inside[u]));
        return best;
    }
};

int main(){
#ifndef LOCAL
    freopen("hub.in","r",stdin);freopen("hub.out","w",stdout);
#endif
    static FastInput in;int c,t;if(!in.read(c))return 0;in.read(t);
    while(t--){int n,k;in.read(n);in.read(k);Tree tr(n);for(int i=1;i<n;i++){int u,v;in.read(u);in.read(v);tr.add(u,v);}if(k==n){puts("0");continue;}Solver solver(tr);int l=1,r=n/2;while(l<r){int m=(l+r)/2;if(solver.minimum(m)<=k)r=m;else l=m+1;}printf("%d\n",l);}
}

Θ(nlog⁡n)\Theta(n\log n)

注意到现在我们不会 1log 维护的是祖先和子树内(uu 这个小树)的情况,它们我们现在都只会 2log。

前者注意到其实只需要上面的“第二类”祖先的深度的限制其实 ≤X−dep(f)+len(f)\le X-dep(f)+len(f) 即可,因此可以前缀和维护。

后者注意到其实是反过来的,相当于子树内有一类点比如叫 zz,就是其子树内只有一条 ≥X\ge X 链,所以现在的限制就是 zz 往上跳至多到 uu 的最长链要 ≥X\ge X。发现这个是一个关于 zz 深度的贡献式子,因此我们直接长剖然后做一个后缀和即可。

注意上面的 len(f)len(f) 如果儿子是最长链上的它的含义会变成次长链。

最后二分后复杂度做到了线性。总复杂度 Θ(nlog⁡n)\Theta(n\log n)。

code
C++
// User-route implementation: see user_route_proof.md for precise definitions.
#include <bits/stdc++.h>
using namespace std;
const int NEG = -1000000007;
struct FastInput {
    static const int S=1<<20; char b[S]; int p=0,len=0;
    int get(){if(p==len){len=fread(b,1,S,stdin);p=0;if(!len)return EOF;}return b[p++];}
    bool read(int &x){int c;do{c=get();if(c==EOF)return false;}while(c<=32);x=0;do{x=x*10+c-'0';c=get();}while(c>='0'&&c<='9');return true;}
};
struct Tree {
    int n,ec=0; vector<int>head,to,nxt;
    Tree(int n):n(n),head(n+1,-1),to(2*n-2),nxt(2*n-2){}
    void add(int u,int v){to[ec]=v;nxt[ec]=head[u];head[u]=ec++;to[ec]=u;nxt[ec]=head[v];head[v]=ec++;}
};
struct Rooted {
    const Tree &tr;int root;
    vector<int>p,dep,ord,h,leaf,sz,heavy,first,second,third,c1,c2,c3,up,upLeaf;
    Rooted(const Tree &t):tr(t),p(t.n+1),dep(t.n+1),h(t.n+1),leaf(t.n+1),sz(t.n+1),heavy(t.n+1),first(t.n+1),second(t.n+1),third(t.n+1),c1(t.n+1),c2(t.n+1),c3(t.n+1),up(t.n+1),upLeaf(t.n+1){ord.reserve(t.n);}
    void build(int r,bool needUp=false){
        root=r;ord.clear();ord.push_back(r);p[r]=0;dep[r]=0;
        // This is a parent-before-child order; later reverse it for tree DP.
        for(size_t i=0;i<ord.size();++i){int u=ord[i];for(int e=tr.head[u];e!=-1;e=tr.nxt[e]){int v=tr.to[e];if(v==p[u])continue;p[v]=u;dep[v]=dep[u]+1;ord.push_back(v);}}
        for(int i=tr.n-1;i>=0;--i){
            int u=ord[i];h[u]=first[u]=second[u]=third[u]=0;leaf[u]=u;sz[u]=1;heavy[u]=c1[u]=c2[u]=c3[u]=0;
            for(int e=tr.head[u];e!=-1;e=tr.nxt[e]){int v=tr.to[e];if(p[v]!=u)continue;
                sz[u]+=sz[v];if(!heavy[u]||sz[v]>sz[heavy[u]])heavy[u]=v;
                int d=h[v]+1;
                if(d>first[u]){third[u]=second[u];c3[u]=c2[u];second[u]=first[u];c2[u]=c1[u];first[u]=d;c1[u]=v;}
                else if(d>second[u]){third[u]=second[u];c3[u]=c2[u];second[u]=d;c2[u]=v;}
                else if(d>third[u]){third[u]=d;c3[u]=v;}
            }
            h[u]=first[u];if(c1[u])leaf[u]=leaf[c1[u]];
        }
        if(needUp){up[r]=0;upLeaf[r]=r;for(int u:ord)for(int e=tr.head[u];e!=-1;e=tr.nxt[e]){int v=tr.to[e];if(p[v]!=u)continue;
            int sibling=c1[u]==v?second[u]:first[u],who=c1[u]==v?c2[u]:c1[u];
            if(up[u]>=sibling)up[v]=up[u]+1,upLeaf[v]=upLeaf[u];
            else up[v]=sibling+1,upLeaf[v]=who?leaf[who]:u;
        }}
    }
    int side(int u,int child)const{return c1[u]==child?second[u]:first[u];}
    int excludingTwo(int u,int a,int b)const{
        if(c1[u]!=a&&c1[u]!=b)return first[u];
        if(c2[u]!=a&&c2[u]!=b)return second[u];
        return third[u];
    }
};
struct MaxSeg {
    int n,s=1;vector<int>a,b;
    MaxSeg(int n):n(n){while(s<n)s<<=1;a.assign(2*s,NEG);b.assign(2*s,NEG);}
    void set(int x,int v,int w){int q=x+s;a[q]=v;b[q]=w;while(q>>=1)a[q]=max(a[q*2],a[q*2+1]),b[q]=max(b[q*2],b[q*2+1]);}
    void build(const vector<int>&v,const vector<int>&w){fill(a.begin(),a.end(),NEG);fill(b.begin(),b.end(),NEG);for(int i=0;i<n;i++)a[s+i]=v[i],b[s+i]=w[i];for(int q=s-1;q;q--)a[q]=max(a[q*2],a[q*2+1]),b[q]=max(b[q*2],b[q*2+1]);}
    int maximum(int l,int r,int type)const{const auto &z=type?b:a;int ans=NEG;for(l+=s,r+=s+1;l<r;l>>=1,r>>=1){if(l&1)ans=max(ans,z[l++]);if(r&1)ans=max(ans,z[--r]);}return ans;}
    int locate(int q,int l,int r,int ql,int qr,int threshold,int type,bool right)const{
        const auto &z=type?b:a;if(r<ql||qr<l||z[q]<threshold)return -1;if(l==r)return l;
        int m=(l+r)/2,t;
        if(right){t=locate(q*2+1,m+1,r,ql,qr,threshold,type,right);if(t!=-1)return t;return locate(q*2,l,m,ql,qr,threshold,type,right);}
        t=locate(q*2,l,m,ql,qr,threshold,type,right);if(t!=-1)return t;return locate(q*2+1,m+1,r,ql,qr,threshold,type,right);
    }
    int find(int l,int r,int t,int type,bool right)const{return l>r?-1:locate(1,0,s-1,l,r,t,type,right);}
};

// The anchor is the R-th ancestor of a deepest leaf in the original rooting.
struct AnchorBase {
    const Tree &tr;Rooted d;vector<int>deepPath,activeSub,prefix;
    AnchorBase(const Tree&t):tr(t),d(t),activeSub(t.n+1),prefix(t.n+1){
        d.build(1);int leaf=d.leaf[1];while(leaf)deepPath.push_back(leaf),leaf=d.p[leaf];
        // deepPath[R] is precisely the required R-th ancestor.
    }
    bool prepare(int R){
        if(R>=(int)deepPath.size()-1)return false;
        d.build(deepPath[R]);
        for(int u:d.ord){int flag=u==d.root||d.h[u]>=R;activeSub[u]=flag;prefix[u]=(d.p[u]?prefix[d.p[u]]:0)+flag;}
        for(int i=tr.n-1;i>0;i--){int u=d.ord[i];activeSub[d.p[u]]+=activeSub[u];}
        return true;
    }
};

struct Solver:AnchorBase {
    vector<int>position,end,pool,inside,D;
    Solver(const Tree&t):AnchorBase(t),position(t.n+1),end(t.n+1),pool(2*t.n+5),inside(t.n+1),D(t.n+1){}
    int minimum(int R){
        if(!R)return tr.n;if(!prepare(R))return 1;
        // Height-heavy (long-chain) decomposition; share the suffix-count buffer.
        int used=d.h[d.root]+2;position[d.root]=0;
        for(int u:d.ord){
            int v=d.c1[u];if(v)position[v]=position[u]+1;
            for(int e=tr.head[u];e!=-1;e=tr.nxt[e]){int w=tr.to[e];if(d.p[w]==u&&w!=v){position[w]=used;used+=d.h[w]+2;}}
        }
        fill(pool.begin(),pool.begin()+used,0);
        for(int i=tr.n-1;i>=0;i--){
            int u=d.ord[i],pos=position[u];
            bool one=d.first[u]>=R&&d.second[u]<R;
            pool[pos]=pool[pos+1]+one;
            if(one){
                int v=d.c1[u];end[u]=min(end[v],pos+R-d.second[u]-1);
                int waiting=pool[pos]-pool[end[u]+1];
                inside[u]=activeSub[u]-waiting;
            }else end[u]=pos-1,inside[u]=activeSub[u];
        }
        int best=activeSub[d.root];D[d.root]=NEG;
        for(int u:d.ord)if(d.p[u]){
            int p=d.p[u],s=d.side(p,u);
            int key=min(d.dep[p],d.dep[p]+s-R);
            D[u]=max(D[p],key);
            int outside=activeSub[d.root]-activeSub[u]-prefix[p]+max(1,D[u]+1);
            best=min(best,outside+max(1,inside[u]));
        }
        return best;
    }
};

int main(){
#ifndef LOCAL
    freopen("hub.in","r",stdin);freopen("hub.out","w",stdout);
#endif
    static FastInput in;int c,t;if(!in.read(c))return 0;in.read(t);
    while(t--){int n,k;in.read(n);in.read(k);Tree tr(n);for(int i=1;i<n;i++){int u,v;in.read(u);in.read(v);tr.add(u,v);}if(k==n){puts("0");continue;}Solver solver(tr);int l=1,r=n/2;while(l<r){int m=(l+r)/2;if(solver.minimum(m)<=k)r=m;else l=m+1;}printf("%d\n",l);}
}
原文
存档评论4 条抓取于