标签:ssi bsp blog begin direction visit mis mode UI
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 17449 Accepted Submission(s): 6747
#include<cstdio> #include<cstdlib> #include<cstring> #include<iostream> #include<algorithm> #define N 41000 using namespace std; int t,n,m,x,y,z,ans,tot; int fa[N],top[N],size[N],deep[N],head[N],dis[N]; struct Edge { int to,dis,from,next; }edge[N<<1]; int add(int x,int y,int z) { tot++; edge[tot].to=y; edge[tot].dis=z; edge[tot].next=head[x]; head[x]=tot; } int read() { int x=0,f=1; char ch=getchar(); while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1; ch=getchar();} while(ch>=‘0‘&&ch<=‘9‘){x=x*10+ch-‘0‘; ch=getchar();} return x*f; } int begin() { ans=0;tot=0; memset(fa,0,sizeof(fa)); memset(top,0,sizeof(top)); memset(dis,0,sizeof(dis)); memset(edge,0,sizeof(edge)); memset(deep,0,sizeof(deep)); memset(size,0,sizeof(size)); memset(head,0,sizeof(head)); } int dfs(int x) { size[x]=1; deep[x]=deep[fa[x]]+1; for(int i=head[x];i;i=edge[i].next) { int to=edge[i].to; if(fa[x]==to) continue; dis[to]=dis[x]+edge[i].dis; fa[to]=x,dfs(to); size[x]+=size[to]; } } int dfs1(int x) { int t=0; if(!top[x]) top[x]=x; for(int i=head[x];i;i=edge[i].next) { int to=edge[i].to; if(fa[x]!=to&&size[t]<size[to]) t=to; } if(t) top[t]=top[x],dfs1(t); for(int i=head[x];i;i=edge[i].next) { int to=edge[i].to; if(fa[x]!=to&&t!=to) dfs1(to); } } int lca(int x,int y) { for(;top[x]!=top[y];x=fa[top[x]]) if(deep[top[x]]<deep[top[y]]) swap(x,y); if(deep[x]>deep[y]) swap(x,y); return x; } int main() { t=read(); while(t--) { n=read();m=read();begin(); for(int i=1;i<n;i++) { x=read(),y=read(),z=read(); add(x,y,z),add(y,x,z); } dfs(1),dfs1(1); for(int i=1;i<=m;i++) { x=read(),y=read(); ans=dis[x]+dis[y]-2*dis[lca(x,y)]; printf("%d\n",ans); } } return 0; }
标签:ssi bsp blog begin direction visit mis mode UI
原文地址:http://www.cnblogs.com/z360/p/7412779.html