bnu 33684 Never Wait for Weights (权值并查集)

Bnu33684Never Wait for Weights

注意:种类并查集要取模,注意有减法时,+MOD

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <ctime>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <string>
#include <set>
#include <stack>
#include <map>
#include <cmath>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

#define FE(i, a, b) for(int i = (a); i <= (b); ++i)
#define FD(i, b, a) for(int i = (b); i >= (a); --i)
#define REP(i, N) for(int i = 0; i < (N); ++i)
#define CLR(a, v) memset(a, v, sizeof(a))
#define PB push_back
#define MP make_pair

#define RI(n) scanf("%d", &n)
#define RIII(a, b, c) scanf("%d%d%d",&a, &b, &c)

typedef long long LL;
const double eps = 1e-10;
const int maxn = 1000010;

int fa[maxn], dis[maxn];

int findset(int x)
{
    if (x != fa[x])
    {
        int fax = fa[x];
        fa[x] = findset(fa[x]);
        dis[x] += dis[fax];
    }
    return fa[x];
}

void Merge(int x, int y, int z)
{
    int fax = findset(x);
    int fay = findset(y);
    if (fax == fay) return ;
    fa[fax] = fay;
    dis[fax] = dis[y] - dis[x] - z;
}

int main()
{
    int n, m;
    char op;
    int x, y, z;
    while (cin >> n >> m && n + m)
    {
        for (int i = 0; i <= n; i++)
            fa[i] = i, dis[i] = 0;
        while (m--)
        {
            scanf(" %c%d%d", &op, &x, &y);
            if (op == '!')
            {
                scanf("%d", &z);
                Merge(x, y, z);
            }
            else
            {
                int fax = findset(x);
                int fay = findset(y);
                if (fax != fay) puts("UNKNOWN");
                else printf("%d\n", dis[y] - dis[x]);
            }
        }
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值