zoukankan      html  css  js  c++  java
  • P1955 [NOI2015]程序自动分析 离散化+并查集

    题目链接 https://www.luogu.com.cn/problem/P1955

    AC代码

    #include<iostream>
    #include <algorithm>
    #include<cstdio>
    using namespace std;
    typedef long long ll;
    
    const int N = 1e6 + 5;
    int a[N][3];
    int b[N + N];
    int par[N+N];
    int rank[N +N];
    void init(int n)
    {
        for (int i = 0; i < n; i++)
        {
            par[i] = i;
            rank[i] = 0;
        }
    }
    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;
        if (rank[x] < rank[y])
        {
            par[x] = y;
        }
        else {
            par[y] = x;
            if (rank[x] == rank[y]) rank[x]++;
        }
    }
    bool same(int x, int y)
    {
        return find(x) == find(y);
    }
    int main()
    {
    
        ios::sync_with_stdio(false);cin.tie(NULL);
        int t;
        cin >> t;
        while (t--)
        {
            int n;
            int j = 0;
    
            cin >> n;
            string s = "YES";
            for (int i = 0; i < n; i++)
            {
                cin >> a[i][0] >> a[i][1] >> a[i][2];
                b[j++] = a[i][0];
                b[j++] = a[i][1];
            }
            sort(b, b + j);
            //debug
            int size = unique(b, b + j) - b;
            for (int i = 0; i < n; i++)
            {
                a[i][0] = lower_bound(b, b + size, a[i][0]) - b;
                a[i][1] = lower_bound(b, b + size, a[i][1]) - b;
            }
            init(N+N);
            for (int i = 0; i < n; i++)
            {
                if (a[i][2] == 1) unite(a[i][0],a[i][1]);
    
            }
            for (int i = 0; i < n; i++)
            {
                if (a[i][2] == 0)
                {
    
                    if (same(a[i][0], a[i][1]))
                        {
                            //debug
                            s = "NO";
                            break;
                        }
                }
            }
            cout << s<< endl;
        }
    }
  • 相关阅读:
    图的深度遍历
    判断森林中有多少棵树
    基于邻接矩阵的广度优先搜索
    第三届程序设计知识竞赛网络赛
    大数相乘
    a+b=x,ab=y
    poj3278
    不敢死队
    单链表中重复元素删除
    poj2506
  • 原文地址:https://www.cnblogs.com/hulian425/p/12221129.html
Copyright © 2011-2022 走看看