标签:
You are given a tree (an undirected acyclic connected graph) with N nodes, and edges numbered 1, 2, 3...N-1. Each edge has an integer value assigned to it, representing its length.
We will ask you to perfrom some instructions of the following form:
Example:
N = 6
1 2 1 // edge connects node 1 and node 2 has cost 1
2 4 1
2 5 2
1 3 1
3 6 2
Path from node 4 to node 6 is 4 -> 2 -> 1 -> 3 -> 6
DIST 4 6 : answer is 5 (1 + 1 + 1 + 2 = 5)
KTH 4 6 4 : answer is 3 (the 4-th node on the path from node 4 to node 6 is 3)
The first line of input contains an integer t, the number of test cases (t <= 25). t test cases follow.
For each test case:
There is one blank line between successive tests.
For each "DIST" or "KTH" operation, write one integer representing its result.
Print one blank line after each test.
Input: 1 6 1 2 1 2 4 1 2 5 2 1 3 1 3 6 2 DIST 4 6 KTH 4 6 4 DONE Output: 5 3
先以一点为根做dfs,计算每个点的深度、父亲、离根的距离,倍增法找出LCA,两点的距离就能算出来了。
路径上的第K个值则先判断LCA到起点的深度差是否大于k,是则在起点到LCA的路径上,否则在LCA到终点的路径上。
#include <iostream> #include <cstdio> #include <cstring> #define N 10005 using namespace std; struct edge{ int to,next,w; }e[N<<1]; int head[N],cnt; void add(int u,int v,int w){ e[++cnt]=(edge){v,head[u],w}; head[u]=cnt; } int n; int deep[N],dis[N],p[N][30]; void dfs(int x,int fa){ deep[x]=deep[fa]+1; p[x][0]=fa; for(int i=0;p[x][i];i++) p[x][i+1]=p[p[x][i]][i];//由x的2^i祖先和祖先的2^i祖先算出x的2^(i+1)祖先 for(int i=head[x];i;i=e[i].next){ int to=e[i].to; if(to==fa)continue; dis[to]=dis[x]+e[i].w; dfs(to,x); } } int lca(int a,int b){ if(deep[a]<deep[b])swap(a,b); for(int j=14;j>=0;j--) if(deep[a]-(1<<j)>=deep[b])//将a上移到和b深度一样 a=p[a][j]; if(a==b)return a; for(int j=14;j>=0;j--) if(p[a][j]&&p[a][j]!=p[b][j]){//a、b一起上移 a=p[a][j]; b=p[b][j]; } return p[a][0]; } int get(int u,int d){//u上升到d深度 for(int j=14;j>=0;j--) if(deep[u]-(1<<j)>=d) u=p[u][j]; return u; } int main() { int t; cin>>t; while(t--){ memset(head,0,sizeof head); memset(p,0,sizeof p);//这个要清空!! cnt=0; cin>>n; for(int i=1;i<n;i++) { int u,v,w; scanf("%d%d%d",&u,&v,&w); add(u,v,w); add(v,u,w); } //deep[0]=0;dis[1]=0;这可以不写 dfs(1,0); char op[100]; while(1){ scanf("%s",op); if(op[1]==‘O‘)break; if(op[1]==‘I‘){ int u,v; scanf("%d%d",&u,&v); printf("%d\n",dis[u]+dis[v]-2*dis[lca(u,v)]); }else{ int u,v,k; scanf("%d%d%d",&u,&v,&k); int fa=lca(u,v),d; if(deep[u]-deep[fa]<k){ d=deep[fa]+k-(deep[u]-deep[fa]+1); u=v; } else d=deep[u]-k+1;//需要的深度 printf("%d\n",get(u,d)); } } } }
【SPOJ QTREE2】QTREE2 - Query on a tree II(LCA)
标签:
原文地址:http://www.cnblogs.com/flipped/p/5827406.html