标签:
题目链接:
Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 32768/32768 K (Java/Others)
#include <bits/stdc++.h> using namespace std; const int N=4e4+4; typedef long long ll; const double PI=acos(-1.0); int n,m,t,dis[N],dep[N],vis[N],w[N]; vector<int>ve[N]; queue<int>qu; int u[N],v[N],d[N],fa[N],a[4*N],tot,first[N]; struct Tree { int l,r,ans; }; Tree tree[8*N]; void bfs()//bfs把图转化成树; { qu.push(1); vis[1]=1; dep[1]=0; while(!qu.empty()) { int top=qu.front(); qu.pop(); int len=ve[top].size(); for(int i=0;i<len;i++) { int x=ve[top][i]; if(!vis[x]) { vis[x]=1; qu.push(x); dep[x]=dep[top]+1; fa[x]=top; } } } } int dfs(int num)//dfs找到lca的数组,并计算i到1的dis { vis[num]=0; first[num]=tot; a[tot++]=num; int len=ve[num].size(); for(int i=0;i<len;i++) { int x=ve[num][i]; if(vis[x]) { dis[x]=dis[num]+d[x]; dfs(x); a[tot++]=num; } } } void Pushup(int node) { if(dep[a[tree[2*node].ans]]>=dep[a[tree[2*node+1].ans]])tree[node].ans=tree[2*node+1].ans; else tree[node].ans=tree[2*node].ans; }//tree[node].ans为数组里的lca的位置; void build(int node,int L,int R) { tree[node].l=L; tree[node].r=R; if(L>=R) { tree[node].ans=L; return ; } int mid=(L+R)>>1; build(2*node,L,mid); build(2*node+1,mid+1,R); Pushup(node); } int query(int node,int L,int R) { if(L<=tree[node].l&&R>=tree[node].r)return tree[node].ans; int mid=(tree[node].l+tree[node].r)>>1; if(R<=mid)return query(2*node,L,R); else if(L>mid)return query(2*node+1,L,R); else { int pos1=query(2*node,L,mid),pos2=query(2*node+1,mid+1,R); if(dep[a[pos1]]>=dep[a[pos2]])return pos2; else return pos1; } } int main() { scanf("%d",&t); while(t--) { scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) { ve[i].clear(); } for(int i=1;i<n;i++) { scanf("%d%d%d",&u[i],&v[i],&w[i]); ve[u[i]].push_back(v[i]); ve[v[i]].push_back(u[i]); } memset(vis,0,sizeof(vis)); bfs(); for(int i=1;i<n;i++) { if(fa[u[i]]==v[i]) { d[u[i]]=w[i]; } else { d[v[i]]=w[i]; } } tot=1; dfs(1); build(1,1,tot-1); int ql,qr; for(int i=0;i<m;i++) { scanf("%d%d",&ql,&qr); int pos; if(first[ql]<=first[qr]) pos=query(1,first[ql],first[qr]); else pos=query(1,first[qr],first[ql]); printf("%d\n",dis[ql]-dis[a[pos]]-dis[a[pos]]+dis[qr]); } } return 0; }
hdu-2586 How far away ?(lca+bfs+dfs+线段树)
标签:
原文地址:http://www.cnblogs.com/zhangchengc919/p/5374442.html