标签:
Time Limit: 2000MS | Memory Limit: 30000K | |
Total Submissions: 11304 | Accepted: 3985 | |
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
离线:将所有查询输入完毕后再统一输出结果。
在线:查询一个输出一个。
dfs+并查集,离线
#include"cstdio" #include"cstring" #include"vector" using namespace std; typedef pair<int,int> P; const int MAXN=100005; int V,E; vector<P> G[MAXN]; vector<P> que[MAXN]; int par[MAXN]; int fnd(int x) { if(par[x]==x) return x; return par[x]=fnd(par[x]); } int vis[MAXN]; int ans[MAXN]; int d[MAXN]; void dfs(int u,int fa) { par[u]=u; for(int i=0;i<que[u].size();i++) { P no=que[u][i]; int v=no.first; if(vis[v]) ans[no.second]=d[u]+d[v]-2*d[fnd(v)]; } vis[u]=1; for(int i=0;i<G[u].size();i++) { P now=G[u][i]; if(now.first==fa) continue; d[now.first]=d[u]+now.second; dfs(now.first,u); par[now.first]=u; } } int main() { while(scanf("%d%d",&V,&E)!=EOF&&V) { for(int i=1;i<=V;i++) { G[i].clear(); que[i].clear(); } memset(vis,0,sizeof(vis)); memset(ans,0,sizeof(ans)); memset(d,0,sizeof(d)); for(int i=0;i<E;i++) { int u,v,cost; scanf("%d %d %d %*c",&u,&v,&cost); G[u].push_back(P(v,cost)); G[v].push_back(P(u,cost)); } int Q; scanf("%d",&Q); for(int i=1;i<=Q;i++) { int u,v; scanf("%d%d",&u,&v); que[u].push_back(P(v,i)); que[v].push_back(P(u,i)); } dfs(1,-1); for(int i=1;i<=Q;i++) { printf("%d\n",ans[i]); } } return 0; }
标签:
原文地址:http://www.cnblogs.com/program-ccc/p/5172370.html