标签:
Description
F1 --- (13) ---- F6 --- (9) ----- F3 | | (3) | | (7) F4 --- (20) -------- F2 | | | (2) F5 | F7
Input
* Line 1: Two space-separated integers: N and M * Lines 2..M+1: Each line contains four space-separated entities, F1, F2, L, and D that describe a road. F1 and F2 are numbers of two farms connected by a road, L is its length, and D is a character that is either ‘N‘, ‘E‘, ‘S‘, or ‘W‘ giving the direction of the road from F1 to F2. * Line M+2: A single integer, K (1 <= K <= 10,000), the number of FB‘s queries * Lines M+3..M+K+2: Each line corresponds to a query from Farmer Bob and contains three space-separated integers: F1, F2, and I. F1 and F2 are numbers of the two farms in the query and I is the index (1 <= I <= M) in the data after which Bob asks the query. Data index 1 is on line 2 of the input data, and so on.
Output
* Lines 1..K: One integer per line, the response to each of Bob‘s queries. Each line should contain either a distance measurement or -1, if it is impossible to determine 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 1 4 3 2 6 6
Sample Output
13 -1 10
Hint
代码:
#include <iostream> #include <cstring> #include <string> #include <cstdio> #include <algorithm> using namespace std; const int N=40005,K=10005; struct node { int x,y,idx,n; }a[K]; //rx,ry 表示相对于原点的距离 int x[N],y[N],dx[N],dy[N],rx[N],ry[N],ans[K],fa[N]; int n,m,k; int find(int x) { if (fa[x]==x) return x; int t=fa[x]; fa[x]=find(fa[x]); //x的rx,ry初始时为0,所以要加上他父亲的 rx[x]+=rx[t]; ry[x]+=ry[t]; return fa[x]; } int cmp(node a,node b) { return a.idx<b.idx; } int main() { int i,j,d,fx,fy; char c; scanf("%d%d",&n,&m); for (i=1;i<=n;i++) { fa[i]=i; rx[i]=ry[i]=0; } for (i=1;i<=m;i++) { scanf("%d%d%d %c",&x[i],&y[i],&d,&c); switch(c) { case 'W':dx[i]=-d;dy[i]=0;break; case 'S':dx[i]=0;dy[i]=-d;break; case 'E':dx[i]=d;dy[i]=0;break; case 'N':dx[i]=0;dy[i]=d;break; } } scanf("%d",&k); for (i=1;i<=k;i++) { scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].idx); a[i].n=i; } sort(a+1,a+k+1,cmp); j=1; for (i=1;i<=k;i++) { for (;j<=a[i].idx;j++) { fx=find(x[j]);fy=find(y[j]); fa[fy]=fx; rx[fy]=rx[x[j]]-rx[y[j]]-dx[j]; ry[fy]=ry[x[j]]-ry[y[j]]-dy[j]; } if (find(a[i].x)!=find(a[i].y)) ans[a[i].n]=-1; else ans[a[i].n]=abs(rx[a[i].x]-rx[a[i].y])+abs(ry[a[i].x]-ry[a[i].y]); } for (i=1;i<=k;i++) printf("%d\n",ans[i]); return 0; }
poj 1984 Navigation Nightmare 并查集 解题报告
标签:
原文地址:http://blog.csdn.net/qq_21899803/article/details/51361118