[Interesting Computer Game](Interesting Computer Game)
题意
T组样例,每一组样例给n组数,每组数仅能取一个数,问能取的不同数的数量最大值。
思路
此题涉及连通分量,但是我还不是很清楚,只能先用我理解的方法来做。
并查集做法,首先必须离散化,kuangbin的标程里离散化操作很标准。
去重后,让每组的两个数相连(做并查集合并),如果并查集内部出现了一次合并查到父节点相同,那么给父节点打上标记(表示这个并查集块里都能选择)。做完之后结算所有并查集父节点,如果其没打上标记,就从总结点里减一(因为这个并查集块里必然有一个不可选择)。
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100010;
int F[MAXN*2];
void init() {
memset(F, -1, sizeof(F));
}
int a[MAXN], b[MAXN];
int c[MAXN*2];
int find(int x) {
if (F[x] == -1) return x;
return F[x] = find(F[x]);
}
bool vis[MAXN*2];
void bing(int x, int y) {
int t1 = find(x);
int t2 = find(y);
if (t1 == t2) {
vis[t1] = true;
return;
}
F[t1] = t2;
if (vis[t1]) vis[t2] = true;
}
int main() {
int T;
scanf("%d", &T);
int iCase = 0;
while (T--) {
iCase++;
init();
memset(vis, false, sizeof(vis));
int n;
scanf("%d", &n);
int tot = 0;
for (int i = 0; i < n; i++) {
scanf("%d%d", &a[i], &b[i]);
c[tot++] = a[i];
c[tot++] = b[i];
}
sort(c, c+tot);
tot = unique(c, c+tot) - c;//离散
for (int i = 0; i < n; i++) {
int x = lower_bound(c, c+tot, a[i]) - c;
int y = lower_bound(c, c+tot, b[i]) - c;
bing(x, y);
}
int ans = tot;
for (int i = 0; i < tot; i++)
if (F[i] == -1 && !vis[i])
ans--;
printf("Case #%d: %d\n", iCase, ans);
}
return 0;
}
/*
1
3
1 2
1 3
3 4
2 3
*/