[NOI2015]程序自动分析

题目描述

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

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

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

输入格式

从文件prog.in中读入数据。

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

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

第1行包含1个正整数n,表示该问题中需要被满足的约束条件个数。接下来n行,每行包括3个整数i,j,e,描述1个相等/不等的约束条件,相邻整数之间用单个空格隔开。若e=1,则该约束条件为xi=xj;若�e=0,则该约束条件为xi≠xj;

输出格式

输出到文件 prog.out 中。

输出文件包括t行。

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

输入输出样例

输入 #1
2
2
1 2 1
1 2 0
2
1 2 1
2 1 1
输出 #1
NO
YES
输入 #2
2
3
1 2 1
2 3 1
3 1 1
4
1 2 1
2 3 1
3 4 1
1 4 0
输出 #2
YES
NO

说明/提示

【样例解释1】

在第一个问题中,约束条件为:x1=x2,x1≠x2。这两个约束条件互相矛盾,因此不可被同时满足。

在第二个问题中,约束条件为:x1=x2,x1=x2。这两个约束条件是等价的,可以被同时满足。

【样例说明2】

在第一个问题中,约束条件有三个:x1=x2,x2=x3,x3=x1。只需赋值使得x1=x1=x1,即可同时满足所有的约束条件。

在第二个问题中,约束条件有四个:x1=x2,x2=x3,x3=x4,x4≠x1。由前三个约束条件可以推出x1=x2=x3=x4,然而最后一个约束条件却要求x1≠x4,因此不可被满足。

【数据范围】

【时限2s,内存512M】

解题思路:离散化+并查集

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <algorithm>
 4 #include <cstring>
 5 #include <string>
 6 #include <cmath>
 7 #include <cstdlib>
 8 using namespace std;
 9 
10 int n,t;
11 const int N=1e5+5;
12 int arr[N],last[2*N];
13 
14 struct Node{
15     int x,y,ff;
16     bool operator<(const Node&X)const{
17         return ff>X.ff;
18     }
19 }A[N];
20 
21 int find_root(int x){
22     return arr[x]==x?x:arr[x]=find_root(arr[x]);
23 }
24 
25 void union_set(int x,int y){
26     int xx=find_root(x);
27     int yy=find_root(y);
28     arr[xx]=yy;
29 }
30 
31 int main(){
32     scanf("%d",&t);
33     while(t--){
34         int tot=-1;
35         memset(last,0,sizeof(last));
36         memset(A,0,sizeof(A));
37         scanf("%d",&n);
38         for(int i=1;i<=n;i++){
39             scanf("%d%d%d",&A[i].x,&A[i].y,&A[i].ff);
40             last[++tot]=A[i].x;
41             last[++tot]=A[i].y;
42         }
43         sort(last,last+tot); //线排序再二分
44         int size=unique(last,last+tot)-last;
45         for(int i=1;i<=n;i++){   //离散化
46             A[i].x=lower_bound(last,last+size,A[i].x)-last;
47             A[i].y=lower_bound(last,last+size,A[i].y)-last;
48         }
49         for(int i=1;i<=size;i++) arr[i]=i;
50         sort(A+1,A+1+n);
51         int flag=1;
52         for(int i=1;i<=n;i++){
53             if(A[i].ff==1) union_set(A[i].x,A[i].y);
54             else{
55                 int xx=find_root(A[i].x);
56                 int yy=find_root(A[i].y);
57                 if(xx==yy) {flag=0;break;}   //矛盾
58             }
59         }
60         printf("%s
",flag==0?"NO":"YES");
61     }
62     return 0;
63 }
View Code
原文地址:https://www.cnblogs.com/qq-1585047819/p/11365203.html