[BZOJ1776] [Usaco2010 Hol]cowpol 奶牛政坛
2015-12-07 17:52
323 查看
传送门
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.
相关文章推荐
- mac svn
- base64与图片之间的转换
- PostgreSQL表空间
- UIView常用属性以及方法
- Huffman学习记录 c语言
- [Javascript Data Structures] 冒泡排序 bubble sort
- 移动端与pc端公用一个域名
- C++类中定义线程
- 表格的变色问题
- 工作流的学习(四)
- waiting for table metadata lock 问题深入分析
- linux sort,uniq,cut,wc,tr命令详解
- Python 元组简单用法
- 工作环境搭建(1) - CentOS7虚拟机的最小化安装
- Hadoop2.6.0学习笔记(八)InputFormat和OutputFormat
- 详解Java线程编程中的volatile关键字的作用
- 数学公式
- Eclipse中Tomcat启动但是不显示Started或Debugging
- JS浮点数(小数)计算加减乘除
- java日期操作