hdu6031 Innumerable Ancestors
来源:互联网 发布:网络接口怎么接线 编辑:程序博客网 时间:2024/06/13 07:01
从现在起,我的标题不写算法了,因为写不下了;
http://acm.hdu.edu.cn/showproblem.php?pid=6031
就是求解A集合和B集合里面的两点的lca的最深深度;
那么我们先预处理树上倍增的东西(就是第i点向上跳2^j步可以到达的位置);
然后直接二分答案k;
找到AB集合里的点在K深度的祖先;
如果两个集合有交集的话就可以;
#include<bits/stdc++.h>#define Ll long longusing namespace std;const int N=1e5+5;struct cs{int to,nxt;}a[N*2];int head[N],ll;int deep[N],f[N][25];bool vi[N];int A[N],B[N],aa,bb,q[N],top;int n,m,x,y,z;void init(int x,int y){ a[++ll].to=y; a[ll].nxt=head[x]; head[x]=ll;}void dfs(int x,int y,int z){ deep[x]=z; f[x][0]=y; for(int k=head[x];k;k=a[k].nxt) if(a[k].to!=y)dfs(a[k].to,x,z+1);}void make(){ for(int j=1;j<=20;j++) for(int i=1;i<=n;i++) if(f[i][j-1]) f[i][j]=f[f[i][j-1]][j-1];}int get(int x,int y){ for(int j=0;y;y>>=1,j++)if(y&1)x=f[x][j]; return x;}bool check(int k){ bool ans=0; for(int i=1;i<=aa;i++) if(deep[A[i]]>=k){ int v=get(A[i],deep[A[i]]-k); q[++top]=v; vi[v]=1; } for(int i=1;i<=bb;i++) if(deep[B[i]]>=k) if(vi[get(B[i],deep[B[i]]-k)])ans=1; while(top)vi[q[top--]]=0; return ans;}int main(){ while(scanf("%d%d",&n,&m)!=-1){ memset(head,0,sizeof head);ll=0; memset(f,0,sizeof f); for(int i=1;i<n;i++){ scanf("%d%d",&x,&y); init(x,y);init(y,x); } dfs(1,0,1); make(); while(m--){ int l=1,r=1,mid,ans=0; scanf("%d",&aa);for(int i=1;i<=aa;i++)scanf("%d",&A[i]),r=max(r,deep[A[i]]); scanf("%d",&bb);for(int i=1;i<=bb;i++)scanf("%d",&B[i]); while(r>=l){ mid=l+r>>1; if(check(mid))ans=max(ans,mid),l=mid+1;else r=mid-1; } printf("%d\n",ans); } }}
这里的二分的范围一定要选对;
如果直接1~20进行二分的话会萎的;
二分的范围一定要精确,不然的话就不满足单调性;
阅读全文
1 0
- hdu6031 Innumerable Ancestors
- HDU6031 Innumerable Ancestors 倍增
- 【HDU6031】Innumerable Ancestors(二分+LCA)
- hdu 6031 Innumerable Ancestors
- HDU6031[Innumerable Ancestor]--二分+倍增思想
- HDU 6031 Innumerable Ancestors[树链剖分]
- HDU 6031 Innumerable Ancestors【LCA】
- HDU 6031 Innumerable Ancestors (LCA)
- HDU 6031 Innumerable Ancestors(LCA,树链剖分)
- hdu 6031 Innumerable Ancestors(LCA+二分)
- hdu 6031 Innumerable Ancestors lca + 二分
- 2017CCPC女生赛 hdu 6031 Innumerable Ancestors
- .ancestors *效果
- Closest Common Ancestors
- POJ1330 Nearest Common Ancestors
- POJ1330(Nearest Common Ancestors)
- poj_1330Nearest Common Ancestors
- poj_1470Closest Common Ancestors
- Mysql NDB and InnoDB 存储引擎区别
- Maven报错:Missing artifact jdk.tools:jdk.tools:jar:1.8
- 总结:改官网首页遇到的问题(一个端整页滚动,一个端正常滚怎么搞)
- [LeetCode 解题报告]012. Integer to Roman
- SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”
- hdu6031 Innumerable Ancestors
- thinkPhp3.2 if判断总结
- $ionicView.afterEnter不触发
- 欢迎使用CSDN-markdown编辑器
- java问答
- 二.验证伪装的代理ip是否成功
- e.getMessage:multiple points
- CRC校验概念及例解
- JAVA 反射常用的三种机制