SPOJ QTREE2 Query on a tree II
2018-08-03 08:44
627 查看
传送门
倍增水题……
本来还想用LCT做的……然后发现根本不需要
倍增水题……
本来还想用LCT做的……然后发现根本不需要
//minamoto #include<bits/stdc++.h> using namespace std; #define getc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++) char buf[1<<21],*p1=buf,*p2=buf; inline int read(){ #define num ch-'0' char ch;bool flag=0;int res; while(!isdigit(ch=getc())) (ch=='-')&&(flag=true); for(res=num;isdigit(ch=getc());res=res*10+num); (flag)&&(res=-res); #undef num return res; } inline bool isop(char ch){ return ch=='I'||ch=='H'||ch=='O'; } inline char readop(){ char ch; while(!isop(ch=getc())); return ch; } const int N=10005; int head ,Next[N<<1],edge[N<<1],ver[N<<1],fa [16],d ,dist ; int n,m,tot; inline void add(int u,int v,int e){ ver[++tot]=v,Next[tot]=head[u],head[u]=tot,edge[tot]=e; ver[++tot]=u,Next[tot]=head[v],head[v]=tot,edge[tot]=e; } void dfs(int u,int f){ d[u]=d[f]+1,fa[u][0]=f; for(int i=1;(1<<i)<=d[u];++i) fa[u][i]=fa[fa[u][i-1]][i-1]; for(int i=head[u];i;i=Next[i]){ int v=ver[i]; if(v==f) continue; dist[v]=dist[u]+edge[i],dfs(v,u); } } int LCA(int x,int y){ if(d[x]<d[y]) swap(x,y); for(int i=15;i>=0;--i) if(d[fa[x][i]]>=d[y]) x=fa[x][i]; if(x==y) return x; for(int i=15;i>=0;--i) if(fa[x][i]!=fa[y][i]) x=fa[x][i],y=fa[y][i]; return fa[x][0]; } int querylen(int x,int y,int k){ int lca=LCA(x,y); if(d[x]-d[lca]+1>=k){ int ans=d[x]-k+1; for(int i=15;i>=0;--i) if((1<<i)<=d[x]-ans) x=fa[x][i]; return x; } else{ int ans=d[lca]*2+k-d[x]-1; for(int i=15;i>=0;--i){ if(d[y]-(1<<i)>=ans) y=fa[y][i]; } return y; } } int main(){ //freopen("testdata.in","r",stdin); int q=read(); while(q--){ memset(head,0,sizeof(head)); memset(fa,0,sizeof(fa)); d[1]=dist[1]=0,tot=0; int n=read(); for(int i=1;i<n;++i){ int u=read(),v=read(),e=read(); add(u,v,e); } dfs(1,0); bool flag=true; while(flag){ char op=readop(); switch(op){ case 'O':flag=false;break; case 'I':{ int u=read(),v=read(); int lca=LCA(u,v); printf("%d\n",dist[u]+dist[v]-2*dist[lca]); break; } case 'H':{ int u=read(),v=read(),k=read(); printf("%d\n",querylen(u,v,k)); break; } } } puts(""); } return 0; }
相关文章推荐
- 【SPOJ QTREE2】QTREE2 - Query on a tree II(LCA)
- 【spoj】【QTREE2 - Query on a tree II】
- SPOJ——QTREE2 - Query on a tree II(树链剖分或者倍增法)
- SPOJ-QTREE2 Query on a tree II(暴力+LCA)
- SPOJ QTREE2 Query on a tree II(lct)
- SPOJ 913 Query on a tree II
- SPOJ 913 Query on a tree II(动态树)
- spoj913 QTREE2 Query on a treeⅡ
- 【SPOJ】913 Query on a tree II QTREE系列之2【LCA】
- SPOJ913 Query on a tree II
- SPOJ Query on a tree II (倍增LCA)
- SPOJ 题目913QTREE2 - Query on a tree II(Link Cut Tree 查询路径第k个点)
- SPOJ Query on a tree II (倍增LCA)
- LCA SP913 QTREE2 - Query on a tree II
- spoj 913 Query on a tree II (倍增lca)
- spoj 913 Query on a tree II 倍增
- SPOJ 913 QTREE系列- Query on a tree II (倍增LCA)
- SPOJ Query on a tree II
- SPOJ Query on a tree II (树剖||倍增LCA)(占位)
- Spoj Query on a tree II (LCA)