Tuesday, August 26, 2014

Getting the Center of a Tree


Credit goes to: Ahmed Ossama, YellowNextYear (codeforces)
 vector<int> getRoots(int n, vector<vector<int> > &children) {
  children.clear();
  children.resize(n);
  vector<int> cnt(n, 0);
  queue<int> Q;
  vector<bool> v(n, 0);
  int x, y, count;
  for (int i = 0; i < n - 1; i++) {
   cin >> x >> y;
   x--;
   y--;
   children[x].pb(y);
   children[y].pb(x);
   cnt[x]++;
   cnt[y]++;
  }
  for (int i = 0; i < n; i++)
   if (cnt[i] == 1)
    Q.push(i);
  count = 0;
  while (!Q.empty()) {
   x = Q.front();
   Q.pop();
   count++;
   v[x] = 1;
   for (int i = 0; i < children[x].size(); i++) {
    y = children[x][i];
    if (cnt[y] == 0) {
     continue;
    }
    cnt[x]--;
    cnt[y]--;
    if (cnt[y] == 1) {
     Q.push(y);
    }
   }
   if (count == n - 2)
    break;
  }
  while (!Q.empty())
   Q.pop();
  vector<int> ret;
  for (int i = 0; i < n; i++) {
   if (v[i] == 0) {
    ret.pb(i);
   }
  }
  return ret;
 }
my method of getting the centers:
bool getRoots(int cur, int parent, int target, int depth, int&length, vector<int>& roots, vector<vector<int> >&t){
 if(target == cur){
  length = depth;
  return true;
 }
 rep(i,sz(t[cur])){
  if(t[cur][i] == parent) continue;
  if(getRoots(t[cur][i],cur,target,depth+1,length,roots,t)){
   if(length/2 == depth || (length+1)/2 == depth)
    roots.pb(cur);
   return true;
  }
 }
 return false;
}
int getFarthest(int cur, vector<vector<int> >&t, int&far,int parent = -1){
 if(parent != -1 && sz(t[cur]) == 1) {
  far = cur;
  return 0;
 }
 int mxDepth = -1, idx = -1;
 rep(i,sz(t[cur])){
  if(parent == t[cur][i]) continue;
  int d, f;
  d = getFarthest(t[cur][i],t,f,cur);
  if(d > mxDepth){
   mxDepth = d;
   idx = f;
  }
 }
 far = idx;
 return mxDepth;
}
vector<int> getRoots(vector<vector<int> >&t){
 int v1, v2;
 getFarthest(0, t, v1);
 getFarthest(v1,t, v2);
 int length = 0;
 vector<int> ret;
 getRoots(v1,-1,v2,0,length,ret,t);
 return ret;
}

No comments:

Post a Comment