Distance Queries
Time Limit: 2000MS | Memory Limit: 30000K | |
Total Submissions: 11304 | Accepted: 3985 | |
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.
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离线:将所有查询输入完毕后再统一输出结果。在线:查询一个输出一个。 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; }