poj - 1984 带权并查集

题意:有多个点,在平面上位于坐标点上,给出一些关系,表示某个点在某个点的正东/西/南/北方向多少距离,然后给出一系列询问,表示在第几个关系给出后询问某两点的曼哈顿距离,或者未知则输出-1。

在权值上保存两个值 : 与祖先在两个方向的差。直接带权并查集

离线数据再处理。

链接:poj 1984

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <vector>
#include <sstream>
#define ll long long

using namespace std;

const int maxn = 100000 + 10;
const int inf = 0x3f3f3f3f;

int father[maxn];
int eh[maxn], nh[maxn];
int a[maxn], b[maxn], l[maxn];
char s[maxn][5];

int n, m, k;

int ans[maxn];

struct node {
    int a, b;
    int num;
    int t;
    friend bool operator < (node a, node b) {
        return a.t < b.t;
    }
}q[maxn];

void init() {
    for(int i = 0; i <= n; i++) {
        father[i] = i;
        eh[i] = nh[i] = 0;
    }
}

int getf(int x) {
    if(father[x] == x) return x;
    int rx = father[x];
    father[x] = getf(father[x]);
    nh[x] += nh[rx];
    eh[x] += eh[rx];
    return father[x];
}

int main()
{
    while(~scanf("%d %d", &n, &m)) {
        for(int i = 1; i <= m; i++) {
            scanf("%d %d %d %s", &a[i], &b[i], &l[i], s[i]);
        }
        scanf("%d", &k);
        for(int i = 1; i <= k; i++) {
            scanf("%d %d %d", &q[i].a, &q[i].b, &q[i].t);
            q[i].num = i;
        }
        sort(q + 1, q + k + 1);
        init();
        int res = 1;
        for(int i = 1; i <= m; i++) {
            int x = getf(a[i]), y = getf(b[i]);
            int nl = 0, el = 0;
            if(s[i][0] == 'N') nl = l[i];
            else if(s[i][0] == 'S') nl = -l[i];
            else if(s[i][0] == 'E') el = l[i];
            else el = -l[i];
            if(x != y) {
                father[x] = y;
                nh[x] = nh[b[i]] + nl - nh[a[i]];
                eh[x] = eh[b[i]] + el - eh[a[i]];
            }
            while(q[res].t == i && res <= k) {
                x = getf(q[res].a), y = getf(q[res].b);
                if(x != y) {
                    ans[q[res].num] = -1;
                }
                else {
                    ans[q[res].num] = abs(nh[q[res].a] - nh[q[res].b]) + abs(eh[q[res].a] - eh[q[res].b]);
                }
                res++;
            }
        }
        for(int i = 1; i <= k; i++) {
            printf("%d\n", ans[i]);
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值