#牛客网 程序自动分析 #并查集 + 离散化

第一眼看这道题秒速写并查集然后WA了,仔细看数据吓了一跳,1e9的数太大,而且数字之间不需要确切的比较,只需要清楚他们的大小关系。所以,对他们进行离散化就ok

下面是AC代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;

int p[maxn], book[maxn], n, res,T; // p和并查集一块用,book表示离散化后的数组
bool flag;
struct node
{
    int x, y, e;
}d[maxn];
bool cmp (node a, node b) {
    return a.e > b.e; // 把e == 1的放前面
}
void init() { // 初始化
    memset(p, 0, sizeof(p));
    memset(d, 0, sizeof(d));
    memset(book, 0, sizeof(book));
    flag = true;
}

int find_(int x) { // 路径压缩
    while (x != p[x]) x = p[x] = p[p[x]];
    return x;
}
void unite(int x, int y) {
    x = find_(x);
    y = find_(y);
    if (x != y) p[x] = y;
}

int main()
{
    cin >> T;
    while (T--) {
        int tot = 0;
        init();
        cin >> n;
        for (int i = 1; i <= n; i++) {
            cin >> d[i].x >> d[i].y >> d[i].e;
            book[tot++] = d[i].x, book[tot++] = d[i].y;
        }
        sort (book, book + tot); // 先排序
        res = unique (book, book + tot) - book; // 再去重
        for (int i = 1; i <= n; i++) {
            d[i].x = lower_bound (book, book + res, d[i].x) - book; // 离散化数字
            d[i].y = lower_bound (book, book + res, d[i].y) - book;
        }
        sort (d + 1, d + n + 1, cmp); // 排序
        for (int i = 1; i <= res; i++) p[i] = i;
        for (int i = 1; i <= n; i++) {
            if (d[i].e) unite(d[i].x, d[i].y);
            else if (!d[i].e &&find_(d[i].x) == find_(d[i].y)) {
                flag = false;
                break;
            }
        }
        if (flag) cout << "YES" << endl;
        else cout << "NO" << endl;
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值