Title Link: http://poj.org/problem?id=1984
Given n cities, the M-bar tells you the relative distance between cities, and the next Q-group asks you to add the distance between the two cities on the first few sides.
#include <iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>#include<stack>#include<map>#include<vector>using namespaceStd;typedefLong LongLL;#definePI 4*atan (1.0)#defineN 42000#defineMet (A, b) memset (A, B, sizeof (a))intF[n], rx[n], ry[n], ans[n];///Rx[i] Represents the offset of x for I and F[i], ry[i] is the offset of y;structnode{intu, V, D, I, Id; Chardir[Ten];} A[n], q[n];intCMP (node p, node Q) {returnp.id<q.id;}intFind (intx) { intK =F[x]; if(x!=F[x]) {F[x]=Find (f[x]); RX[X]+=Rx[k]; RY[X]+=Ry[k]; } returnf[x];}voidUnion (intnum) { intx = a[num].u, y =a[num].v; CharCH = a[num].dir[0]; intpx = Find (x), py =Find (y); if(px! =py) {F[PX]=py; RX[PX]= Rx[y]-Rx[x]; RY[PX]= Ry[y]-Ry[x]; if(ch = ='E') rx[px]-=A[NUM].D; if(ch = ='W') rx[px]+=A[NUM].D; if(ch = ='N') ry[px]-=A[NUM].D; if(ch = ='S') ry[px]+=A[NUM].D; }}intMain () {intN, M, Q; while(SCANF ("%d%d", &n, &m)! =EOF) {Met (A,0); Met (Q,0); Met (ans,0); for(intI=0; i<=n; i++) F[i]= i, rx[i] = ry[i] =0; for(intI=1; i<=m; i++) scanf ("%d %d%d%s", &a[i].u, &A[I].V, &a[i].d, A[i].dir); scanf ("%d", &p); for(intI=1; i<=q; i++) {scanf (" %d%d%d", &q[i].u, &Q[I].V, &Q[i]. I); Q[i]. Id=i; } sort (Q+1, q+q+1, CMP);///It is not possible to sort, because it is given in the order of I; for(intPre=0, i=1; i<=q; i++) { for(intJ=pre+1; J<=q[i]. I; J + +) Union (j); Pre=Q[i]. I; intU = q[i].u, v =q[i].v; intPX =Find (U); intPY =Find (v); if(px! = py) Ans[q[i]. ID] =-1; ElseAns[q[i]. ID] = ABS (RX[U]-RX[V]) + ABS (ry[u]-Ry[v]); } for(intI=1; i<=q; i++) printf ("%d\n", Ans[i]); } return 0;}
Navigation Nightmare---poj1984 (multi-relationship and collection)