食物链 POJ - 1182

这个是挑战程序那本书上的代码,自己实现了一下。

#include <iostream>
#include <stdio.h>

using namespace std;

//const int MAX_N = 100000 + 7;

int N, K;
//int T[MAX_N], X[MAX_N], Y[MAX_N];

int f[3 * 50000 + 7];

int find (int x) {
	if (x != f[x])
		f[x] = find(f[x]);
	return f[x];
}

void unite (int x, int y) {
	int fx = find (x);
	int fy = find (y);
	if (fx != fy) 
		f[f[x]] = fy;
}

bool same (int x, int y) {
	return find(x) == find(y);
}

void init (int n) {
	for (int i = 1; i <= n; i++)
		f[i] = i;
}

void solve () {
	init (N * 3);
	
	int ans = 0;
	for (int i = 0; i < K; ++i) {
		int t, x, y;
		scanf ("%d%d%d", &t, &x, &y);
//		cin >> t >> x >> y;
		x --; y --;
		//int t = T[i];               //  类型 
		//int x = X[i] - 1, y = Y[i] - 1;   //  
		
		if (x < 0 || N <= x || y < 0 || N <= y) {
			ans ++;
			continue;
		}

		if (t == 1) {
			if (same (x, y + N) || same (x, y + 2 * N)) {
				ans ++;
			} else {
				unite (x, y);
				unite (x + N, y + N);
				unite (x + 2 * N, y + 2 * N);
			}
		} else {
			if (same (x, y) || same (x, y + 2 * N)) {
				ans ++;
			} else {
				unite (x, y + N);
				unite (x + N, y + 2 * N);
				unite (x + 2 * N, y);
			}
		}
	}
	
	cout << ans << endl;
}

int main () {
	cin >> N >> K;
//	for (int i = 0; i < K; ++i) {
//		cin >> T[i] >> X[i] >> Y[i];
//	}
	solve ();
	return 0;
} 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值