题目链接
#include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
#include <math.h>
using namespace std;
const int maxn= 4e4 + 5 ;
int n, m;
struct node
{
int fa, lenx, leny;
node ( int x= 0 , int y= 0 , int z= 0 )
{
fa= x, lenx= y, leny= z;
}
} Node[ maxn] ;
int findfa ( int x)
{
if ( Node[ x] . fa== x)
return x;
int t= Node[ x] . fa;
Node[ x] . fa= findfa ( Node[ x] . fa) ;
Node[ x] . lenx+ = Node[ t] . lenx;
Node[ x] . leny+ = Node[ t] . leny;
return Node[ x] . fa;
}
int num[ maxn] [ 3 ] ; char dir[ maxn] ;
int main ( )
{
ios: : sync_with_stdio ( false) ;
cin>> n>> m;
for ( int i= 1 ; i<= n; i++ )
Node[ i] . fa= i;
for ( int i= 0 ; i< m; i++ )
cin>> num[ i] [ 0 ] >> num[ i] [ 1 ] >> num[ i] [ 2 ] >> dir[ i] ;
int i= 0 ;
int q; cin>> q;
while ( q-- )
{
int x, y, idx;
cin>> x>> y>> idx;
for ( ; i< idx; i++ )
{
int X= num[ i] [ 0 ] , Y= num[ i] [ 1 ] ;
int fx= findfa ( X) , fy= findfa ( Y) ;
if ( fx== fy)
continue ;
Node[ fx] . fa= fy;
if ( dir[ i] == 'E' )
{
Node[ fx] . lenx= num[ i] [ 2 ] - Node[ X] . lenx+ Node[ Y] . lenx;
Node[ fx] . leny= Node[ Y] . leny- Node[ X] . leny;
}
else if ( dir[ i] == 'W' )
{
Node[ fx] . lenx= - num[ i] [ 2 ] - Node[ X] . lenx+ Node[ Y] . lenx;
Node[ fx] . leny= Node[ Y] . leny- Node[ X] . leny;
}
else if ( dir[ i] == 'N' )
{
Node[ fx] . lenx= Node[ Y] . lenx- Node[ X] . lenx;
Node[ fx] . leny= Node[ Y] . leny- Node[ X] . leny+ num[ i] [ 2 ] ;
}
else if ( dir[ i] == 'S' )
{
Node[ fx] . lenx= Node[ Y] . lenx- Node[ X] . lenx;
Node[ fx] . leny= Node[ Y] . leny- Node[ X] . leny- num[ i] [ 2 ] ;
}
}
int fx= findfa ( x) , fy= findfa ( y) ;
if ( fx!= fy)
cout<< - 1 << endl;
else
cout<< int ( fabs ( Node[ x] . lenx- Node[ y] . lenx) + fabs ( Node[ x] . leny- Node[ y] . leny) ) << endl;
}
return 0 ;
}