标签:des style blog http color os strong io
传送门:
http://poj.org/problem?id=1986
Time Limit: 2000MS | Memory Limit: 30000K | |
Case Time Limit: 1000MS |
Description
Input
Output
Sample Input
7 6 1 6 13 E 6 3 9 E 3 5 7 S 4 1 3 N 2 4 20 W 4 7 2 S 3 1 6 1 4 2 6
Sample Output
13 3 36
Hint
Source
1 #include<set> 2 #include<queue> 3 #include<cstdio> 4 #include<cstdlib> 5 #include<cstring> 6 #include<iostream> 7 #include<algorithm> 8 using namespace std; 9 const int N = 100010; 10 #define For(i,n) for(int i=1;i<=n;i++) 11 #define Rep(i,l,r) for(int i=l;i<=r;i++) 12 13 struct Edge{ 14 int t,next,w; 15 }E[N*2]; 16 vector< pair<int,int> > Q[N]; 17 int s,t,w,Es,ans[N],head[N],fa[N],d[N]; 18 bool vis[N]; 19 20 int find(int i){ 21 if(fa[i]==i) return i; 22 else return find(fa[i]); 23 } 24 25 void makelist(int s,int t,int w){ 26 E[Es].t = t; E[Es].w = w;E[Es].next = head[s]; 27 head[s] = Es++; 28 } 29 30 void LCA(int i,int w){ 31 d[i] = w;fa[i] = i; 32 vis[i] = true; 33 for(int p=head[i];p!=-1;p=E[p].next) 34 if(!vis[E[p].t]){ 35 LCA(E[p].t,w+E[p].w); 36 fa[E[p].t] = i; 37 } 38 int len = Q[i].size(); 39 for(int j=0;j<len;j++){ 40 if(vis[Q[i][j].first]) 41 ans[Q[i][j].second] = w + d[Q[i][j].first] - 2 * d[find(Q[i][j].first)]; 42 } 43 } 44 int n,m,qn; 45 int main(){ 46 memset(head,-1,sizeof(head)); 47 scanf("%d%d",&n,&m); 48 For(i,m){ 49 scanf("%d%d%d %*c",&s,&t,&w); 50 makelist(s,t,w);makelist(t,s,w); 51 } 52 scanf("%d",&qn); 53 For(i,qn){ 54 scanf("%d%d",&s,&t); 55 Q[s].push_back(make_pair(t,i));Q[t].push_back(make_pair(s,i)); 56 } 57 LCA(1,0); 58 For(i,qn) printf("%d\n",ans[i]); 59 return 0; 60 }
POJ1986 Distance Queries (LCA),布布扣,bubuko.com
POJ1986 Distance Queries (LCA)
标签:des style blog http color os strong io
原文地址:http://www.cnblogs.com/kjerome/p/3888352.html