洛谷p1955 (NOI2015)

2 篇文章 0 订阅
1 篇文章 0 订阅

题目思路并不复杂…只要想到并查集就好…
不过还有一点…xi和xj数可能很大,那么我们是不可能搞那么大的数组的…所有应该利用map或者哈希之类的离散化到一个比较小的范围内…
对于所有要求相等的条件,把xi和xj合并,所有相等的都合并之后,开始检查不相等的条件,此时如果发现条件中有一组数之前已经被合并了,那么说明这个问询是有矛盾存在的。

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<map>
using namespace std;
struct query {
    int x, y;
};
query q[1000001];
int par[2000005];
int find(int x)
{
    if (par[x] == x)return x;
    else return par[x] = find(par[x]);
}
void unite(int x, int y)
{
    x = find(x), y = find(y);
    if (x == y)return;
    par[y] = x;
}
int main()
{
    int t, n, i, j;
    cin >> t;
    while (t--) {
        cin >> n; int cnt1 =0, cnt2 = 0;
        for (i = 1; i <= 2*n; i++)
            par[i] = i;
        map<int, int>hash1;
        map<int, int>::iterator iter;
        for (i = 1; i <= n; i++) {
            int a, b, c;
            scanf("%d %d %d", &a, &b, &c);
            if ((iter = hash1.find(a)) == hash1.end()) {
                hash1.insert(pair<int, int>(a, ++cnt1)); a = cnt1;
            }
            else
                a = iter->second;
            if ((iter = hash1.find(b)) == hash1.end()) {
                hash1.insert(pair<int, int>(b, ++cnt1)); b = cnt1;
            }
            else
                b = iter->second;
            if (c == 1)
                //q1[++cnt1].x = a, q1[cnt1].y = b;
                unite(a, b);
            else
                q[++cnt2].x = a, q[cnt2].y = b;
        }
        bool check = true;
        for (i = 1; i <= cnt2; i++) {
            if (find(q[i].x) == find(q[i].y)) {
                check = false; break;
            }
        }
        if (check)cout << "YES" << endl;
        else cout << "NO" << endl;
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值