http://poj.org/problem?id=1986
Time Limit: 2000MS | Memory Limit: 30000K | |
Total Submissions: 14383 | Accepted: 5063 | |
Case Time Limit: 1000MS |
Description
Farmer John's cows refused to run in his marathon since he chose a path much too long for their leisurely lifestyle. He therefore wants to find a path of a more reasonable length. The input to this problem consists of the same input as in "Navigation Nightmare",followed by a line containing a single integer K, followed by K "distance queries". Each distance query is a line of input containing two integers, giving the numbers of two farms between which FJ is interested in computing distance (measured in the length of the roads along the path between the two farms). Please answer FJ's distance queries as quickly as possible!
Input
* Lines 1..1+M: Same format as "Navigation Nightmare"
* Line 2+M: A single integer, K. 1 <= K <= 10,000
* Lines 3+M..2+M+K: Each line corresponds to a distance query and contains the indices of two farms.
* Line 2+M: A single integer, K. 1 <= K <= 10,000
* Lines 3+M..2+M+K: Each line corresponds to a distance query and contains the indices of two farms.
Output
* Lines 1..K: For each distance query, output on a single line an integer giving the appropriate distance.
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
Farms 2 and 6 are 20+3+13=36 apart.
Source
方向~~~忽悠人的。。。
1 #include <algorithm> 2 #include <cstdio> 3 4 using namespace std; 5 6 const int N(53333); 7 char s[3]; 8 int n,m,dis[N],head[N],sumedge; 9 struct Edge 10 { 11 int v,w,next; 12 Edge(int v=0,int next=0,int w=0): 13 v(v),next(next),w(w){} 14 }edge[N<<1]; 15 inline void ins(int u,int v,int w) 16 { 17 edge[++sumedge]=Edge(v,head[u],w); 18 head[u]=sumedge; 19 } 20 21 int size[N],top[N],dad[N],son[N],deep[N]; 22 void DFS(int u,int fa,int deepth) 23 { 24 dad[u]=fa; 25 size[u]=1; 26 deep[u]=deepth; 27 for(register int v,i=head[u];i;i=edge[i].next) 28 { 29 v=edge[i].v; 30 if(dad[u]==v) continue; 31 dis[v]=dis[u]+edge[i].w; 32 DFS(v,u,deepth+1); 33 size[u]+=size[v]; 34 if(size[son[u]]<size[v]) son[u]=v; 35 } 36 } 37 void DFS_(int u,int Top) 38 { 39 top[u]=Top; 40 if(son[u]) DFS_(son[u],Top); 41 for(int v,i=head[u];i;i=edge[i].next) 42 { 43 v=edge[i].v; 44 if(dad[u]!=v&&son[u]!=v) DFS_(v,v); 45 } 46 } 47 int LCA(int x,int y) 48 { 49 for(;top[x]!=top[y];x=dad[top[x]]) 50 if(deep[top[x]]<deep[top[y]]) swap(x,y); 51 return deep[x]<deep[y]?x:y; 52 } 53 54 int main() 55 { 56 scanf("%d%d",&n,&m); 57 for(int u,v,w;m--;) 58 { 59 scanf("%d%d%d%s",&u,&v,&w,s); 60 ins(u,v,w); ins(v,u,w); 61 } 62 DFS(1,0,1); DFS_(1,1); 63 int k;scanf("%d",&k); 64 for(int u,v;k--;) 65 { 66 scanf("%d%d",&u,&v); 67 printf("%d ",dis[v]+dis[u]-dis[LCA(u,v)]*2); 68 } 69 return 0; 70 }