标签:size log scanf default ext lock desc icon ddl
http://codevs.cn/problem/2370/
2370 小机房的树
#include<bits/stdc++.h> using namespace std; #define maxn 10000000 int n,head[maxn],m,s,x,y,z,num; int size[maxn],deep[maxn],dad[maxn],top[maxn],dis[maxn]; struct Edge{ int u,v,next,w; }edge[maxn]; void ins(int u,int v,int w) { edge[++num].next=head[u]; edge[num].v=v; edge[num].w=w; head[u]=num; } void dfs(int x) { size[x]=1 ; deep[x]=deep[dad[x]]+1; for(int i=head[x];i;i=edge[i].next) { int v=edge[i].v; if(dad[x]==v) continue; dad[v]=x; dis[v]=dis[x]+edge[i].w; dfs(v); size[x]+=size[v]; } } void dfs2(int x) { int t=0; if(!top[x]) top[x]=x; for(int i=head[x];i;i=edge[i].next) { int v=edge[i].v; if(dad[x]!=v&&size[t]<size[v]) t=v; } if(t) top[t]=top[x],dfs2(t); for(int i=head[x];i;i=edge[i].next) { int v=edge[i].v; if(dad[x]!=v&&t!=v) dfs2(v); } } int lca(int x,int y) { for(;top[x]!=top[y];x=dad[top[x]]) if(deep[top[x]]<deep[top[y]]) swap(x,y); return deep[x]<deep[y]?x:y; } int main() { scanf("%d",&n); for(int i=1;i<n;i++) { scanf("%d%d%d",&x,&y,&z); ins(x,y,z); ins(y,x,z); } dfs(0); dfs2(0); scanf("%d",&m); for(int i=1;i<=m;i++) { scanf("%d%d",&x,&y); int a=lca(x,y); printf("%d\n",dis[x]+dis[y]-2*dis[a]); } return 0; }
标签:size log scanf default ext lock desc icon ddl
原文地址:http://www.cnblogs.com/chen74123/p/7400125.html