标签:父节点 led 比较 art scan memory name sub 端点
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<vector> 6 using namespace std; 7 int n,k,root,ans,mxdeep,mx; 8 int father[200010],group[200010],deep[200010],fa[200010][32]; 9 vector<int>child[200010],party[200010]; 10 void dfs(int u){ 11 fa[u][0]=father[u]; 12 deep[u]=deep[father[u]]+1; 13 for(int i=1;(1<<i)<=n;i++) fa[u][i]=fa[fa[u][i-1]][i-1]; 14 for(int i=0;i<child[u].size();i++) dfs(child[u][i]); 15 } 16 int lca(int u,int v){ 17 if(deep[u]<deep[v]) swap(u,v); 18 int i=0; 19 for(i=0;(1<<i)<=n;i++); 20 i--; 21 for(int j=i;j>=0;j--) 22 if(deep[u]-(1<<j)>=deep[v]) u=fa[u][j]; 23 if(u==v) return u; 24 for(int j=i;j>=0;j--) 25 if(fa[u][j]!=fa[v][j]){ 26 u=fa[u][j]; 27 v=fa[v][j]; 28 } 29 return father[u]; 30 } 31 int main(){ 32 scanf("%d%d",&n,&k); 33 for(int i=1;i<=n;i++){ 34 scanf("%d%d",&group[i],&father[i]); 35 child[father[i]].push_back(i); 36 party[group[i]].push_back(i); 37 if(!father[i]) root=i; 38 } 39 dfs(root); 40 for(int i=1;i<=k;i++){ 41 ans=0; 42 mxdeep=0; 43 mx=0; 44 for(int j=0;j<party[i].size();j++) 45 if(deep[party[i][j]]>mxdeep){ 46 mxdeep=deep[party[i][j]]; 47 mx=party[i][j]; 48 } 49 for(int j=0;j<party[i].size();j++) 50 ans=max(ans,deep[mx]+deep[party[i][j]]-2*deep[lca(mx,party[i][j])]); 51 printf("%d\n",ans); 52 } 53 return 0; 54 }
标签:父节点 led 比较 art scan memory name sub 端点
原文地址:http://www.cnblogs.com/sdfzxh/p/6935583.html