AcWing 237. 程序自动分析
原题链接
中等
作者:
acw_weian
,
2020-09-06 22:32:30
,
所有人可见
,
阅读 511
- 离散化
- 并查集, 合并所有相等的节点, 因为=号有传递性
- 查找 != 的数字, 判断他们是否在同一个集合
import java.io.*;
import java.util.*;
class Main{
static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
static int N = 1000010, idx = 1;
static int[] f = new int[N];
static Map<Integer, Integer> map = new HashMap();
static List<int[]> list = new ArrayList();
public static int get(int a){
if(!map.containsKey(a)){
map.put(a, idx++);
}
return map.get(a);
}
public static void main(String[] args) throws Exception{
int t = Integer.valueOf(read.readLine());
while(t -- > 0){
map.clear();
list.clear();
int n = Integer.valueOf(read.readLine());
idx = 1;
for(int i = 0; i <= n * 2; i++) f[i] = i;
for(int i = 0; i < n; i++){
String[] ss = read.readLine().split(" ");
int a = get(Integer.valueOf(ss[0]));
int b = get(Integer.valueOf(ss[1]));
if("1".equals(ss[2].trim())){
int f1 = find(a), f2 = find(b);
if(f1 != f2){
f[f1] = f2;
}
}else{
list.add(new int[]{a, b});
}
}
boolean fake = false;
for(int i = 0; i < list.size(); i++){
int a = list.get(i)[0];
int b = list.get(i)[1];
int f1 = find(a), f2 = find(b);
if(f1 == f2){
fake = true;
break;
}
}
if(fake) System.out.println("NO");
else System.out.println("YES");
}
}
public static int find(int x){
if(f[x] != x) f[x] = find(f[x]);
return f[x];
}
}