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

传送门

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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值