[BZOJ1776] [Usaco2010 Hol]cowpol 奶牛政坛

来源:互联网 发布:页面加载后执行js 编辑:程序博客网 时间:2024/05/15 12:51

传送门

http://www.lydsy.com/JudgeOnline/problem.php?id=1776

题目大意

给定一棵有m种颜色染色的树,询问每种颜色中距离最远两点的距离

题解

距离最远两点中的一点一定为该种颜色中深度最大的点(这个证明可以参照树的直径的证明),然后枚举另一点求lca求距离判断即可

var st:array[0..200005,0..30]of longint; w,u:array[0..600005,1..2]of longint; t,dep:array[0..200005]of longint; i,j,k:longint; n,m,len1,len2,head,tail,tt,v,a,b,root,ans,maxd:longint;procedure init1(a,b:longint);begin w[len1,1]:=b; if w[a,2]=0 then w[a,2]:=len1 else w[w[a,1],2]:=len1; w[a,1]:=len1; inc(len1);end;procedure init2(a,b:longint);begin u[len2,1]:=b; if u[a,2]=0 then u[a,2]:=len2 else u[u[a,1],2]:=len2; u[a,1]:=len2; inc(len2);end;function lca(a,b:longint):longint;var i:longint;begin if dep[a]>dep[b] then begin i:=a; a:=b; b:=i; end; for i:=trunc(ln(maxd)/ln(2)) downto 0 do  if dep[st[b,i]]>=dep[a] then b:=st[b,i]; if a=b then exit(a); for i:=trunc(ln(maxd)/ln(2)) downto 0 do  if st[a,i]<>st[b,i]  then begin a:=st[a,i]; b:=st[b,i]; end; exit(st[a,0]);end;begin readln(n,m); len1:=n+1; len2:=m+1; for i:=1 to n do  begin   readln(a,b);   if b=0 then root:=i;   init1(b,i); st[i,0]:=b; init2(a,i);  end; dep[root]:=1; t[1]:=root; head:=1; tail:=2; maxd:=1; while head<tail do  begin   v:=t[head]; inc(head); tt:=w[v,2];   while tt<>0 do    begin     dep[w[tt,1]]:=dep[v]+1;     if dep[v]+1>maxd then maxd:=dep[v]+1;     t[tail]:=w[tt,1]; inc(tail);     tt:=w[tt,2];    end;  end; for j:=1 to trunc(ln(maxd)/ln(2)) do  for i:=1 to n do   st[i,j]:=st[st[i,j-1],j-1]; dep[0]:=0; for i:=1 to m do  begin   tt:=u[i,2]; k:=0;   while tt<>0 do    begin     if dep[u[tt,1]]>dep[k]     then k:=u[tt,1];     tt:=u[tt,2];    end;   tt:=u[i,2]; ans:=0;   while tt<>0 do    begin     j:=lca(k,u[tt,1]);     if dep[k]+dep[u[tt,1]]-2*dep[j]>ans     then ans:=dep[k]+dep[u[tt,1]]-2*dep[j];     tt:=u[tt,2];    end;   writeln(ans);  end;end.
0 0