Brain Network (hard) CodeForces - 690C 简单倍增 + 一些有趣的推导

Code:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 200000 + 4;
const int logn = 19;
int F[30][maxn], dep[maxn];
inline int lca(int a,int b)
{
   if(dep[a] > dep[b]) swap(a,b);
   if(dep[a] != dep[b])
   {
       for(int i = logn;i >= 0;--i) if(dep[F[i][b]] >= dep[a]) b = F[i][b];
   }
   if(a == b) return a;
   for(int i = logn; i >= 0; --i)
   {
       if(F[i][a] != F[i][b]) a = F[i][a], b = F[i][b];
   }
   return F[0][a];
}
int main()
{
  // freopen("input.txt","r",stdin);
   int n, point1 = 1, point2 = 1;
   scanf("%d",&n);
   dep[1] = 1;
   for(int i = 2;i <= n; ++i)
   {
       int fa; scanf("%d",&fa);
       F[0][i] = fa, dep[i] = dep[fa] + 1;
       for(int j = 1;j <= logn; ++j)F[j][i] = F[j - 1][F[j-1][i]];
       int ans1 = dep[point1] + dep[point2] - 2 * dep[lca(point1,point2)];
       int ans2 = dep[point1] + dep[i] - 2 * dep[lca(point1, i)]; 
       int ans3 = dep[point2] + dep[i] - 2 * dep[lca(point2, i)];
       int maxv = max(ans1, max(ans2, ans3));
       printf("%d\n",maxv);
       if(ans1 == maxv) continue;
       if(ans2 == maxv) point2 = i;
       else if(ans3 == maxv) point1 = i;
   }
   return 0;
}
posted @ 2018-09-17 19:25  EM-LGH  阅读(223)  评论(0编辑  收藏  举报