Navigation Nightmare POJ

#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
const int N=4e4+10;
//        东西   南北 
int p[N],D[N],B[N];
struct node{
    int x,y,d;
    char op[5];
}e[N];
void init()
{
    for(int i = 0 ; i < N ; i ++)
    {
        p[i] =i;
        D[i] =0;
        B[i] =0;
        e[i].x=0,e[i].y=0,e[i].d=0;
    }
}
int find(int x)
{
    if(p[x]!=x)
    {
        int root=find(p[x]);
        D[x]+=D[p[x]];
        B[x]+=B[p[x]];
        p[x]=root;
    }
    return p[x];
}
void build(int x,int y,int d,char opr[])
{
    int dx=find(x);
    int dy=find(y);
    if(dx!=dy)
    {
        p[dy]=dx;
        //这里虽然是在东西方向,但是南北方向的权值数组也是要更新的因为a在b的正西方向d米
        //其实是a在b东西方向,向西移动d米加上a在b南北方向上移动0米 
        if(opr[0]=='E'||opr[0]=='W')
        {
            //如果和正方向相同就是加上这个距离,规定东为正方向
            if(opr[0]=='E')
                D[dy]=D[x]-D[y]+d;
            if(opr[0]=='W')
                D[dy]=D[x]-D[y]-d;
            B[dy]=B[x]-B[y];//什么都不加
        }
        else if(opr[0]=='N'||opr[0]=='S')
        {
            if(opr[0]=='N') 
                B[dy]=B[x]-B[y]+d;
            if(opr[0]=='S') 
                B[dy]=B[x]-B[y]-d;
            D[dy]=D[x]-D[y];
        }
    }
}
int main()
{
    int n,m;
    while(cin>>n>>m)
    {
        init();
        for(int i=1;i<=m;i++)
            cin>>e[i].x>>e[i].y>>e[i].d>>e[i].op;
        int t;
        cin>>t;
        int cnt=1;
        //c其实就是按照从小到大的方式输入
        //所以我们可以边输入边建立 
        int ans;
        for(int i=0;i<t;i++)
        {
            int a,b,c;
            cin>>a>>b>>c;
            //在c之前的我们都给他建立了 
            while(cnt<=c)
            {
                build(e[cnt].x,e[cnt].y,e[cnt].d,e[cnt].op);
                cnt++;
            }
            int da=find(a);
            int db=find(b);
            if(da!=db)
                ans=-1;
            else
                ans=abs(D[a]-D[b])+abs(B[a]-B[b]);
            cout<<ans<<endl;
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/QingyuYYYYY/p/12250207.html