题解【洛谷P1955】[NOI2015]程序自动分析

题面

我们发现 (i, j) 的范围很大,于是先进行离散化把数据范围映射成 (1sim 2 imes n)

然后我们先进行 (e=1) 的操作,用一个并查集维护相等的关系。

然后对于 (e=0),如果两个数在同一个集合中,则直接输出 NO

整个过程没有输出 NO 就在最后输出 YES

注意多测要初始化。

#include <bits/stdc++.h>
#define DEBUG fprintf(stderr, "Passing [%s] line %d
", __FUNCTION__, __LINE__)
#define File(x) freopen(x".in","r",stdin); freopen(x".out","w",stdout)

using namespace std;

typedef long long LL;
typedef pair <int, int> PII;
typedef pair <int, PII> PIII;

inline int gi()
{
	int f = 1, x = 0; char c = getchar();
	while (c < '0' || c > '9') {if (c == '-') f = -1; c = getchar();}
	while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
	return f * x;
}

inline LL gl()
{
	LL f = 1, x = 0; char c = getchar();
	while (c < '0' || c > '9') {if (c == '-') f = -1; c = getchar();}
	while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
	return f * x;
}

const int INF = 0x3f3f3f3f, N = 1000003;

int n, T;
int d[N * 2], tot;
int fa[N * 2];
struct Node
{
    int a, b, id;
} x[N];

inline bool cmp(Node x, Node y)
{
    return x.id > y.id;
}

int getf(int u) {return fa[u] == u ? u : fa[u] = getf(fa[u]);}

int main()
{
	//File("");
    T = gi();
    while (T--)
    {
        n = gi();
        tot = 0;
        for (int i = 1; i <= n; i+=1) 
        {
            x[i].a = gi(), x[i].b = gi(), x[i].id = gi();
            d[++tot] = x[i].a, d[++tot] = x[i].b;
        }
        sort(d + 1, d + 1 + tot);
        int cnt = unique(d + 1, d + 1 + tot) - d - 1;
        sort(x + 1, x + 1 + n, cmp);
        for (int i = 1; i <= n * 2; i+=1) fa[i] = i;
        bool fl = true;
        for (int i = 1; i <= n; i+=1) 
        {
            x[i].a = lower_bound(d + 1, d + 1 + cnt, x[i].a) - d;
            x[i].b = lower_bound(d + 1, d + 1 + cnt, x[i].b) - d;
            if (x[i].id) fa[getf(x[i].a)] = getf(x[i].b);
            else 
            {
                if (getf(x[i].a) == getf(x[i].b)) 
                {
                    puts("NO");
                    fl = false;
                    break;
                }
            }
        }
        if (fl) puts("YES");
    }
	return 0;
}
原文地址:https://www.cnblogs.com/xsl19/p/12725868.html