标签:oss lsp sea 方向 swap targe dad space continue
Time Limit: 2000MS | Memory Limit: 30000K | |
Total Submissions: 14383 | Accepted: 5063 | |
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 <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\n",dis[v]+dis[u]-dis[LCA(u,v)]*2); 68 } 69 return 0; 70 }
标签:oss lsp sea 方向 swap targe dad space continue
原文地址:http://www.cnblogs.com/Shy-key/p/7409888.html