1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
| #include <stdio.h> #include <string.h> #include <stdlib.h> #include <algorithm> using namespace std;
const int MAX_N = 40010; int nN, nM; int nSets[MAX_N]; int nX[MAX_N]; int nY[MAX_N]; char szInput[MAX_N][100];
void MakeSets(int nNum) { for (int i = 0; i < nNum; ++i) { nSets[i] = i; nX[i] = nY[i] = 0; } }
int FindSets(int nI) { if (nSets[nI] != nI) { int nPre = nSets[nI]; nSets[nI] = FindSets(nSets[nI]); nX[nI] += nX[nPre]; nY[nI] += nY[nPre]; } return nSets[nI]; }
void UnionSets(int nBeg, int nEnd, int dx, int dy) { int nA = FindSets(nBeg); int nB = FindSets(nEnd); if (nA != nB) { nSets[nB] = nA; nX[nB] = nX[nBeg] + dx - nX[nEnd]; nY[nB] = nY[nBeg] + dy - nY[nEnd]; } }
int main() { int nBeg, nEnd, nL; char szDir[10];
while (scanf("%d%d%*c", &nN, &nM) == 2) { MakeSets(nN); for (int i = 0; i < nM; ++i) { fgets(szInput[i], 100, stdin); } int nK; int nF1, nF2, nI; scanf("%d", nK); int nCur = 0; while (nK--) { scanf("%d%d%d", nF1, nF2, nI); for (int i = nCur; i < nI; ++i) { sscanf(szInput[i], "%d%d%d%s", &nBeg, &nEnd, &nL, szDir); int dx = 0, dy = 0; switch (szDir[0]) { case 'N': dy += nL; break; case 'S': dy -= nL; break; case 'E': dx += nL; break; case 'W': dx -= nL; break; } UnionSets(nBeg, nEnd, dx, dy); } nCur = nI;
if (FindSets(nF1) != FindSets(nF2)) { printf("-1\n"); } else { printf("%d\n", abs(nX[nF1] - nX[nF2]) + abs(nY[nF1] - nY[nF2])); } } }
return 0; }
|