acwing-239. 奇偶游戏(经典带权并查集)

  • 关键在于公式的推导,将集合B合并至A后,要做好对原本B集合的根的新权值的计算
#include
#include
#define f(i,a,b) for(int i=a;i<=b;++i)
#define fd(i,a,b) for(int i=a;i>=b;--i)
#define debug(x) cerr<<#x<<": "<<x<<endl;
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N = 505, M = 2e5 + 50;
map<int, int> mp;
int idx;
int get(int x) {
	if (!mp.count(x))mp[x] = ++idx;
	return mp[x];
}
int fa[10004],dis[10004];
int find(int x) {
	if (fa[x] != x) {
		int root = find(fa[x]);//get new fa
		dis[x] ^= dis[fa[x]];//upd the new value
		fa[x] = root;//path shrink
	}
	return fa[x];
}
int main()
{
#ifndef ONLINE_JUDGE
	freopen("in.txt", "r", stdin);
#endif
	//食物链简化版:带权并查集合
	//如何合并:考虑式子推导,用dis[a],dis[b]表示a,b到当前其父节点的距离奇偶性
	//用fa,fb表示a,b所在集合的根
	//用dis(x)表示将fb插入fa后,集合fb中所有元素的新距离
	//1.dis(b)=dis[b]^dis(fb)
	//2.希望得到的dis(b)满足dis(b)^dis[a]=k(0或者1)
	//=>3.dis(fb)^dis[b]^dis[a]=k
	//<=>4.dis(fb)=dis[a]^dis[b]^k
	int n;cin >> n;;
	int q;cin >> q;
	f(i, 1,10004)fa[i] = i;
	int res = q;
	f(i,1,q){
		int a, b;
		scanf("%d%d", &a, &b);
		string op;cin >> op;
		int k = op == "even" ? 0 : 1;
		a = get(a - 1), b = get(b);
		int fx = find(a), fy = find(b);
		if (fx == fy) {
			if (dis[a] ^ dis[b] ^ k == 1) {
				res = i - 1;
				break;
			}
		}
		else {
			fa[fy] = fx;
			dis[fy] = dis[a] ^ dis[b] ^ k;
		}
	}
	cout << res << endl;
	return 0;
}

你可能感兴趣的:(恢复训练,游戏,c++,算法)