Hadoop2.4.0 Eclipse插件制作
tarjanLCA求树上任意两点间的距离。。。。
任意选一个点当根节点,dist[a,b]= dist[a] +dist[b] -2* lca[a,b]
How far away ?
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4254 Accepted Submission(s): 1622
For each test case,in the first line there are two numbers n(2<=n<=40000) and m (1<=m<=200),the number of houses and the number of queries. The following n-1 lines each consisting three numbers i,j,k, separated bu a single space, meaning that there is a road connecting house i and house j,with length k(0<k<=40000).The houses are labeled from 1 to n.
Next m lines each has distinct integers i and j, you areato answer the distance between house i and house j.
2 3 2 1 2 10 3 1 15 1 2 2 3 2 2 1 2 100 1 2 2 1
10 25 100 100
#include <iostream> #include <cstring> #include <cstdio> #include <algorithm> using namespace std; const int maxn=44000; struct Edge { int to,next,distan; }edge[2*maxn],edge2[maxn]; int Adj[maxn],Adj2[maxn],Size,Size2; void init_1() { Size=0; memset(Adj,-1,sizeof(Adj)); } void init_2() { Size2=0; memset(Adj2,-1,sizeof(Adj2)); } void Add_Edge(int u,int v,int c) { edge[Size].to=v; edge[Size].next=Adj[u]; edge[Size].distan=c; Adj[u]=Size++; } void Add_Edge2(int u,int v,int id) { edge2[Size2].to=v; edge2[Size2].next=Adj2[u]; edge2[Size2].distan=id; Adj2[u]=Size2++; } int n,m; int fa[maxn]; int Find(int x) { if(x==fa[x]) return x; return fa[x]=Find(fa[x]); } bool vis[maxn]; int Distan[maxn],ans[maxn]; void LCA(int u,int father) { for(int i=Adj[u];~i;i=edge[i].next) { int v=edge[i].to; if(v==father) continue; Distan[v]=Distan[u]+edge[i].distan; LCA(v,u); fa[v]=u; } vis[u]=true; for(int i=Adj2[u];~i;i=edge2[i].next) { int v=edge2[i].to; int id=edge2[i].distan; if(vis[v]) { ans[id]=Distan[u]+Distan[v]-2*Distan[Find(v)]; } } } int main() { int T_T; scanf("%d",&T_T); while(T_T--) { init_1();init_2(); scanf("%d%d",&n,&m); fa[0]=0;fa[1]=1;fa[2]=2; for(int i=0;i<n-1;i++) { int a,b,c; scanf("%d%d%d",&a,&b,&c); Add_Edge(a,b,c); Add_Edge(b,a,c); fa[i+3]=i+3; } for(int i=0;i<m;i++) { int a,b; scanf("%d%d",&a,&b); Add_Edge2(a,b,i); Add_Edge2(b,a,i); } memset(Distan,0,sizeof(Distan)); memset(ans,0,sizeof(ans)); memset(vis,false,sizeof(vis)); LCA(1,1); for(int i=0;i<m;i++) printf("%d\n",ans[i]); } return 0; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。