标签:following mit java length nbsp ace ati led ber
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 17447 Accepted Submission(s): 6745
题目大意:给定n个点和n-1条边,询问两点间的最短距离
解题思路:LCA离线。上一题的代码就改了下输入。。。(http://www.cnblogs.com/WWkkk/p/7409868.html)
#include<cstdio> #include<vector> #include<algorithm> using namespace std; const int maxn=1e5+10; struct node { int v,c; }; vector<node>tree[maxn],que[maxn]; int dis[maxn],num[maxn],f[maxn]; bool vis[maxn]; void Init(int n) { for(int i=0;i<=n;i++) { tree[i].clear(); que[i].clear(); f[i] = i; dis[i] = 0; num[i] = 0; vis[i] = 0; } } int Find(int x) { int r=x; while(r!=f[r]) { r = f[r]; } while(x!=f[x]) { int j=f[x]; f[x] = r; x = j; } return x; } void lca(int u) { vis[u] = true; f[u] = u; for(int i=0;i<que[u].size();i++) { int v = que[u][i].v; if(vis[v]) { num[que[u][i].c]=dis[v]+dis[u]-2*dis[Find(v)]; } } for(int i=0;i<tree[u].size();i++) { int v=tree[u][i].v; if(!vis[v]) { dis[v] = dis[u]+tree[u][i].c; lca(v); f[v] = u; } } } int main() { int x,y,c,n,q,t; scanf("%d",&t); while(t--) { scanf("%d %d",&n,&q); Init(n); for(int i=0;i<n-1;i++) { scanf("%d %d %d",&x,&y,&c); node temp; temp.v = y; temp.c = c; tree[x].push_back(temp); temp.v = x; tree[y].push_back(temp); } for(int i=0;i<q;i++) { scanf("%d %d",&x,&y); node temp; temp.v = y; temp.c = i; que[x].push_back(temp); temp.v = x; que[y].push_back(temp); } lca(1); for(int i=0;i<q;i++) printf("%d\n",num[i]); } }
标签:following mit java length nbsp ace ati led ber
原文地址:http://www.cnblogs.com/WWkkk/p/7409915.html