Advertisement
istinishat

Centroid Decompositon

May 2nd, 2018
355
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //source : http://codeforces.com/contest/321/submission/23347823
  2. // theory : https://threads-iiith.quora.com/Centroid-Decomposition-of-a-Tree
  3.  
  4. #include<bits/stdc++.h>
  5. using namespace std;
  6.  
  7. #define si(n) scanf("%d",&n)
  8. #define MAX 100005
  9.  
  10. vector<int>gr[MAX];
  11. int n,tot_node;
  12. int sz[MAX],ans[MAX];
  13.  
  14. void go(int now,int pr)
  15. {
  16.     tot_node++;
  17.     sz[now]=1;
  18.     for(int i=0;i<gr[now].size();i++){
  19.         int to=gr[now][i];
  20.         if(to==pr || ans[to]!=-1)continue;
  21.         go(to,now);
  22.         sz[now]+=sz[to];
  23.     }
  24. }
  25.  
  26. int go2(int now,int pr)
  27. {
  28.     for(int i=0;i<gr[now].size();i++){
  29.         int to=gr[now][i];
  30.         if(to == pr || ans[to] !=-1)continue;
  31.         if(sz[to]>tot_node/2)return go2(to,now);
  32.     }
  33.     return now;
  34. }
  35.  
  36. void decompose(int now,int par,int level)
  37. {
  38.     tot_node=0;
  39.     go(now,par);
  40.     int centroid=go2(now,par);
  41.     //cout<<centroid<<endl;
  42.     ans[centroid]=level;
  43.  
  44.  
  45.     for(int i=0;i<gr[centroid].size();i++){
  46.         int to=gr[centroid][i];
  47.         if(ans[to]!=-1)continue;
  48.         decompose(to,now,level+1);
  49.     }
  50. }
  51.  
  52.  
  53. int main()
  54. {
  55.     //freopen("input.txt","r",stdin);
  56.     int i,j;
  57.     si(n);
  58.     for(i=1;i<n;i++){
  59.         int u,v;
  60.         si(u);si(v);
  61.         gr[u].push_back(v);
  62.         gr[v].push_back(u);
  63.     }
  64.     memset(ans,-1,sizeof(ans));
  65.     decompose(1,-1,0);
  66.     for(i=1;i<=n;i++){
  67.         //cout<<i<<' '<<ans[i]<<endl;
  68.         printf("%c ",ans[i]+'A');
  69.     }
  70.  
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement