4195: [Noi2015]程序自动分析
Time Limit: 10 Sec Memory Limit: 512 MBSubmit: 1716 Solved: 767
[ Submit][ Status][ Discuss]
Description
在实现程序自动分析的过程中,常常需要判定一些约束条件是否能被同时满足。
考虑一个约束满足问题的简化版本:假设x1,x2,x3,…代表程序中出现的变量,给定n个形如xi=xj或xi≠xj的变量相等/不等的约束条件,请判定是否可以分别为每一个变量赋予恰当的值,使得上述所有约束条件同时被满足。例如,一个问题中的约束条件为:x1=x2,x2=x3,x3=x4,x1≠x4,这些约束条件显然是不可能同时被满足的,因此这个问题应判定为不可被满足。
现在给出一些约束满足问题,请分别对它们进行判定。
Input
输入文件的第1行包含1个正整数t,表示需要判定的问题个数。注意这些问题之间是相互独立的。
对于每个问题,包含若干行:
第1行包含1个正整数n,表示该问题中需要被满足的约束条件个数。
接下来n行,每行包括3个整数i,j,e,描述1个相等/不等的约束条件,相邻整数之间用单个空格隔开。若e=1,则该约束条件为xi=xj;若e=0,则该约束条件为xi≠xj。
Output
输出文件包括t行。
输出文件的第k行输出一个字符串“YES”或者“NO”(不包含引号,字母全部大写),“YES”表示输入中的第k个问题判定为可以被满足,“NO”表示不可被满足。
Sample Input
2
2
1 2 1
1 2 0
2
1 2 1
2 1 1
2
1 2 1
1 2 0
2
1 2 1
2 1 1
Sample Output
NO
YES
YES
HINT
在第一个问题中,约束条件为:x1=x2,x1≠x2。这两个约束条件互相矛盾,因此不可被同时满足。
在第二个问题中,约束条件为:x1=x2,x2=x1。这两个约束条件是等价的,可以被同时满足。
1≤n≤1000000
1≤i,j≤1000000000
Source
离散化+并查集。。。纯属凑经验
#include<iostream>
#include<cstring>
#include<vector>
#include<queue>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<bitset>
using namespace std;
const int maxn = 1E6 + 10;
int T,n,cur,ta,tb,tot,fa[maxn],A[maxn*2],xa[maxn],ya[maxn],xb[maxn],yb[maxn];
int getfa(int x) {return x == fa[x]?x:fa[x] = getfa(fa[x]);}
int getint()
{
char ch = getchar(); int ret = 0;
while (ch < '0' || '9' < ch) ch = getchar();
while ('0' <= ch && ch <= '9')
ret = ret*10 + ch - '0',ch = getchar();
return ret;
}
int main()
{
#ifdef DMC
freopen("DMC.txt","r",stdin);
#endif
T = getint();
while (T--)
{
n = getint(); tot = ta = tb = 0; cur = 1;
for (int i = 1; i <= n; i++)
{
int a = getint(),b,c;
b = getint(); c = getint();
if (c) xa[++ta] = a,ya[ta] = b;
else xb[++tb] = a,yb[tb] = b;
A[++tot] = a; A[++tot] = b;
}
sort(A + 1,A + tot + 1);
for (int i = 2; i <= tot; i++)
if (A[i] != A[i-1]) A[++cur] = A[i];
for (int i = 1; i <= cur; i++) fa[i] = i;
for (int i = 1; i <= ta; i++)
{
int x = lower_bound(A + 1,A + cur + 1,xa[i]) - A;
int y = lower_bound(A + 1,A + cur + 1,ya[i]) - A;
int fx = getfa(x),fy = getfa(y);
if (fx == fy) continue;
fa[fx] = fy;
}
bool pass = 1;
for (int i = 1; i <= tb; i++)
{
int x = lower_bound(A + 1,A + cur + 1,xb[i]) - A;
int y = lower_bound(A + 1,A + cur + 1,yb[i]) - A;
int fx = getfa(x),fy = getfa(y);
if (fx == fy) {pass = 0; break;}
}
if (pass) puts("YES"); else puts("NO");
}
return 0;
}