[并查集]程序自动分析

题目:

在实现程序自动分析的过程中,常常需要判定一些约束条件是否能被同时满足。

考虑一个约束满足问题的简化版本:假设x1,x2,x3,…x1,x2,x3,…代表程序中出现的变量,给定n个形如xi=xjxi=xj或xi≠xjxi≠xj的变量相等/不等的约束条件,请判定是否可以分别为每一个变量赋予恰当的值,使得上述所有约束条件同时被满足。

例如,一个问题中的约束条件为:x1=x2,x2=x3,x3=x4,x1≠x4x1=x2,x2=x3,x3=x4,x1≠x4,这些约束条件显然是不可能同时被满足的,因此这个问题应判定为不可被满足。

现在给出一些约束满足问题,请分别对它们进行判定。

输入格式

输入文件的第1行包含1个正整数t,表示需要判定的问题个数,注意这些问题之间是相互独立的。

对于每个问题,包含若干行:

第1行包含1个正整数n,表示该问题中需要被满足的约束条件个数。

接下来n行,每行包括3个整数i,j,e,描述1个相等/不等的约束条件,相邻整数之间用单个空格隔开。若e=1,则该约束条件为xi=xjxi=xj;若e=0,则该约束条件为xi≠xjxi≠xj。

输出格式

输出文件包括t行。

输出文件的第k行输出一个字符串“YES”或者“NO”(不包含引号,字母全部大写),“YES”表示输入中的第k个问题判定为可以被满足,“NO”表示不可被满足。

解题思路:

把所有相等的关系建立集合, 不等的如果在一个相等的集合里则不符合题意, 反着来也行

离散化+sort操作

/*
    Zeolim - An AC a day keeps the bug away
*/

//pragma GCC optimize(2)
#include <cstdio>
#include <iostream>
#include <bitset>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <sstream>
#include <map>
#include <ctime>
#include <vector>
#include <fstream>
#include <list>
#include <iomanip>
#include <numeric>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
const ld PI = acos(-1.0);
const ld E = exp(1.0);
const int INF = 0x3f3f3f3f;
const int MAXN = 1e6 + 10;
const ll MOD = 1e9 + 7;

int fa[MAXN] = {0};

vector <ll> node;

void lsh()
{
	sort(node.begin(), node.end());
	node.erase(unique(node.begin(), node.end()), node.end());
}

int retpos(ll x)
{
	return lower_bound(node.begin(), node.end(), x) - node.begin();
}

struct op
{
	ll a, b;
	bool ok;
}arr[MAXN];

bool cmp(op a, op b)
{
	return a.ok > b.ok;
}

int findfa(int x)
{
	return fa[x] == x ? x : fa[x] = findfa(fa[x]);
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);     cout.tie(0);
    //freopen("D://test.in", "r", stdin);
    //freopen("D://test.out", "w", stdout);

	int n;

	cin >> n;

	while(n--)
	{
		int t;

		cin >> t;

		node.clear();

		for(int i = 0; i < t; ++i)
		{
			cin >> arr[i].a >> arr[i].b >> arr[i].ok;
			node.push_back(arr[i].a), node.push_back(arr[i].b);
		}

		lsh();

		for(int i = 0; i <= node.size(); ++i)
			fa[i] = i;

		bool flag = true;
	
		sort(arr, arr + t, cmp);
		
		for(int i = 0; i < t && flag; ++i)
		{
			int p = findfa(retpos(arr[i].a)), q = findfa(retpos(arr[i].b));

			if(arr[i].ok)
			{
				fa[p] = q;
			}
			
			else
			{
				if(fa[p] == q)
					flag = false;
			}
		}

		if(flag)
			cout << "YES\n";
		else
			cout << "NO\n";
	}

    return 0;
}

 

posted @ 2019-05-07 21:50  张浦  阅读(113)  评论(0编辑  收藏  举报