Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 59208 | Accepted: 17321 |
Description
Input
Output
Sample Input
100 7 1 101 1 2 1 2 2 2 3 2 3 3 1 1 3 2 3 1 1 5 5
Sample Output
3
详解地址
http://blog.csdn.net/c0de4fun/article/details/7318642
《挑战程序设计竞赛》解法
#include <cstdio> using namespace std; int t, n, k, x, y; int par[150010]; void init(int n) { for (int i = 1; i < 3 * n; i++) par[i] = i; } int find(int x) { if (par[x] == x) return x; else return par[x] = find(par[x]); } void unite(int x, int y) { int u = find(x); int v = find(y); if (u != v) par[u] = v; } bool same(int x, int y) { return find(x) == find(y); } int main() { int ans = 0; scanf("%d%d", &n, &k); init(n); while (k--){ scanf("%d%d%d", &t, &x, &y); if (x > n || y > n){ 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 + n * 2, y + n * 2); } } else{ if (same(x, y) || same(x, y + n * 2)) ans++; else{ unite(x, y + n); unite(x + n, y + 2 * n); unite(x + 2 * n, y); } } } printf("%d\n", ans); return 0; }