[Codeforces208E]Blood Cousins(dsu on the tree+倍增)
来源:互联网 发布:mill9.1软件下载 编辑:程序博客网 时间:2024/05/08 03:59
题目描述
传送门
题意:给出一棵家谱树,定义向上走k步到达的节点为该点的k-ancestor。每次询问与v同P-ancestor的节点有多少个。
题解
题目可以转化为在v的P-ancestor的子树里和v同一深度的有多少个点
用dsu on the tree搞一搞。。
倍增求出v的P-ancestor,然后对于每一个询问加一个链表,一遍dfs就行了。
注意这是一个森林
时间复杂度
代码
#include<algorithm>#include<iostream>#include<cstring>#include<cstdio>#include<cmath>using namespace std;#define N 100005#define sz 17int n,m,Son;int tot,point[N],nxt[N],v[N];int cq,pq[N],nxtq[N],vq[N],idq[N];int root[N],size[N],h[N],f[N][sz],son[N],cnt[N],ans[N];void add(int x,int y){ ++tot; nxt[tot]=point[x]; point[x]=tot; v[tot]=y;}void addq(int x,int y,int z){ ++cq; nxtq[cq]=pq[x]; pq[x]=cq; vq[cq]=y; idq[cq]=z;}void build(int x,int dep){ size[x]=1;h[x]=dep; for (int i=1;i<sz;++i) f[x][i]=f[f[x][i-1]][i-1]; for (int i=point[x];i;i=nxt[i]) { f[v[i]][0]=x; build(v[i],dep+1); size[x]+=size[v[i]]; if (size[v[i]]>size[son[x]]) son[x]=v[i]; }}int find(int x,int y){ for (int i=0;i<sz;++i) if ((y>>i)&1) x=f[x][i]; return x;}void calc(int x,int opt){ cnt[h[x]]+=opt; for (int i=point[x];i;i=nxt[i]) if (v[i]!=Son) calc(v[i],opt);}void dfs(int x,int k){ for (int i=point[x];i;i=nxt[i]) if (v[i]!=son[x]) dfs(v[i],0); if (son[x]) dfs(son[x],1),Son=son[x]; calc(x,1);Son=0; for (int i=pq[x];i;i=nxtq[i]) { int H=vq[i]; ans[idq[i]]=cnt[H]-1; } if (!k) calc(x,-1);}int main(){ scanf("%d",&n); for (int i=1;i<=n;++i) { int fa;scanf("%d",&fa); if (!fa) root[++root[0]]=i; add(fa,i); } for (int i=1;i<=root[0];++i) build(root[i],1); scanf("%d",&m); for (int i=1;i<=m;++i) { int x,y,z;scanf("%d%d",&x,&y); z=find(x,y); addq(z,h[x],i); } for (int i=1;i<=root[0];++i) dfs(root[i],0); for (int i=1;i<=m;++i) printf("%d%c",ans[i]," \n"[i==m]);}
0 0
- [Codeforces208E]Blood Cousins(dsu on the tree+倍增)
- [codeforces208E]Blood Cousins(dsu on the tree+倍增)
- codeforces 208 E. Blood Cousins (dsu on the tree)
- [Codeforces246E]Blood Cousins Return(dsu on the tree+set)
- [codeforces246E]Blood Cousins Return(dsu on the tree+STL)
- codeforces 246 E. Blood Cousins Return (set+dsu on the tree)
- codeforces 570 D. Tree Requests (dsu on the tree)
- [Codeforces570D]Tree Requests(dsu on the tree)
- [Codeforces375D]Tree and Queries(dsu on the tree+bit)
- [codeforces570D]Tree Requests(dsu on the tree)
- [codeforces375D]Tree and Queries(dsu on the tree+bit)
- codeforces 600 E. Lomsat gelral (dsu on the tree)
- [Codeforces600E]Lomsat gelral(dsu on the tree)
- [codeforces600E]Lomsat gelral(dsu on the tree+讲解)
- dsu on the tree 学习笔记
- [trick]dsu on tree
- dsu on tree
- [trick]dsu on tree
- caffe下用FCN做图像分割,如何制作训练集?
- Linux下JDK、Tomcat的安装及配置
- 2016亚洲区域赛现场赛北京赛区e题
- GYM 100090 M.Jumping along the Hummocks(SPFA)
- PTA 5-18 打印学生选课清单 (25分)【】
- [Codeforces208E]Blood Cousins(dsu on the tree+倍增)
- 50个Java多线程面试题
- 文章标题
- Windows XP将显示桌面放到任务栏
- JAVA多线程——Thread和Runnable的区别
- fedora打开VMware共享文件夹功能
- java实现对称加密(3DES)
- 设计模式——策略模式
- R语言列表循环添加元素