map暴力? 90pt #2 没过, 求调
查看原帖
map暴力? 90pt #2 没过, 求调
384370
fattership楼主2023/4/22 21:38

在你们看我代码的时候我可能已经做出来了,注意评论

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <unordered_map>

using namespace std;

const int N = (int)1e9+100;

// 使用特殊map来防止TLE 
unordered_map<long long, long long> fa;

// 找到root 
long long findRt(long long x) {
	return fa[x] = (fa[x]==x?x:findRt(fa[x]));
}

// 合并,从大的合并到小的,保证顺序 
void conv(long long x, long long y) {
	long long fx, fy;
	fx = findRt(x);
	fy = findRt(y);
	if(fx!=fy) {
		if(fx > fy) {
			swap(fx, fy);
		}
		fa[fy] = fx;
	} 
}

int main() {
	int t;
	cin >> t;
	while (t--) {
		fa.clear();
		int n;
		scanf("%d", &n);
		// 类型, 集合1, 集合2 
		long long t, x, y;
		// 很傻的解决方式 
		bool s = true;
		for(int i=0; i<n; i++) {
			scanf("%lld%lld%lld", &x, &y, &t);
			
			// 有结果就直接continue掉, 数据消掉就行 
			if(!s) {
				continue;
			}
			
			// 动态初始化,避免内存飙升到6个g 
			if(fa[x]==0) {
				fa[x] = x;
				fa[x+N] = x+N;
			}
			if(fa[y]==0) {
				fa[y] = y;
				fa[y+N] = y+N;
			}
			
			// 各自的根节点 
			x = findRt(x);
			y = findRt(y);
			
			if(t==1) {
				// 判断(敌人的敌人是朋友 
				if(findRt(x) == findRt(y+N)) {
					s = false;
					continue;
				}
				conv(x, y); 
				conv(x+N, y+N); 
			}
			if(t==0) {
				// 判断(朋友就是朋友 
				if(findRt(x) == findRt(y)) {
					s = false;
					continue;
				}
				conv(x, y+N); 
				conv(x+N, y); 
			}
		}
		// 输出 
		if(s) {
			printf("YES\n");
		} else {
			printf("NO\n");
		} 
	}
	return 0;
} 
2023/4/22 21:38
加载中...