cf 1009F

之前写过一个类似的。600E
考虑到记录的信息与子树的深度是相关的,所以我们长链剖分
不是啊我怎么就快了100ms啊我写了个假的???
然后启发式合并,更新答案还是蛮好更新的。

#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N = 1e6+5;
vector<int> g[N];
int n,sz[N],hson[N],dep[N],id[N],ans[N],mxd[N];
map<int,int> mp[N];
map<int,int>::iterator it;
void pdfs(int v,int d,int far){
    dep[v]=d;sz[v]=d;
    for(auto u:g[v]){
        if(u==far)continue;
        pdfs(u,d+1,v);
        if(!hson[v]||sz[u]>sz[v])
            hson[v]=u;
        sz[v]=max(sz[v],sz[u]+1);
    }
}
void dfs(int v,int fa){
    for(auto u:g[v]){
        if(u==fa)continue;
        dfs(u,v);
    }
    if(hson[v]){
        swap(mp[v],mp[hson[v]]);
        mp[v][dep[v]]++;
        mxd[v]=mxd[hson[v]];
        ans[v]=ans[hson[v]]+1;
        if(mxd[v]==1)ans[v]=0;
    }else{
        mp[v][dep[v]]++;
        mxd[v]=1;
    }
    for(auto u:g[v]){
        if(u==hson[v]||u==fa)continue;
        for(it=mp[u].begin();it!=mp[u].end();it++){
            int k = it->first;
            mp[v][k]+=it->second;
            int val=mp[v][k];
            if(val>mxd[v]) {
                mxd[v] = val;
                ans[v] = k-dep[v];
            }else if(val==mxd[v]){
                ans[v]=min(ans[v],k-dep[v]);
            }
        }
    }
}
int main(){
    ios::sync_with_stdio(false);
    cin>>n;
    for(int i=1,x,y;i<n;i++){
        cin>>x>>y;
        g[x].push_back(y);
        g[y].push_back(x);
    }
    pdfs(1,0,0);
    dfs(1,1);
    for(int i=1;i<=n;i++)cout<<ans[i]<<'
';
}
原文地址:https://www.cnblogs.com/MXang/p/11360508.html