The Suspects
AC代码:
#include <map>
#include <set>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <cstdio>
#include <cctype>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define LL long long
#define INF 0x7fffffff
using namespace std;
int n, m;
const int maxn = 30005;
int pa[maxn];
int tot[maxn];//记录当前集合的总数
int find(int x) {
return pa[x] == x ? x : pa[x] = find(pa[x]);//带路径压缩
}
void link(int x, int y) {
int px = find(x);
int py = find(y);
if(px == py) return;
pa[px] = py;
tot[py] += tot[px];
}
int main() {
while(scanf("%d %d", &n, &m) != EOF) {
if(n == 0 && m == 0) break;
for(int i = 0; i <= n; i ++) {
pa[i] = i;
tot[i] = 1;
}
int k, h, s;
for(int i = 0; i < m; i ++) {
scanf("%d", &k);
scanf("%d", &h);
for(int j = 1; j < k; j ++) {
scanf("%d", &s);
link(h, s);
}
}
printf("%d\n", tot[find(0)]);
}
return 0;
}
Cube Stacking
题目传送:POJ - 1988 - Cube Stacking
AC代码:
#include <map>
#include <set>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <cstdio>
#include <cctype>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define LL long long
#define INF 0x7fffffff
using namespace std;
const int maxn = 30005;
int pa[maxn];
int under[maxn];
int sum[maxn];
int p;
int find(int x) {
if(x == pa[x]) {
return x;
}
int t = find(pa[x]);
under[x] += under[pa[x]];//路径压缩的时候要更新under数组,且这个数组只能放这里,因为要先更新祖先
pa[x] = t;
return pa[x];
}
void link(int x, int y) {//把x所在的堆放到y所在的堆上
int px = find(x);
int py = find(y);
if(px == py) {
return;
}
pa[px] = py;
under[px] = sum[py];//将下面那个堆的总数更新到上面那个堆的根
sum[py] += sum[px];//计算现在这个堆的总数,不能和上面那个位置互换
}
int main() {
while(scanf("%d", &p) != EOF) {
for(int i = 0; i < maxn; i ++) {
pa[i] = i;
under[i] = 0;
sum[i] = 1;
}
char op[15];
int a, b;
for(int i = 0; i < p; i ++) {
scanf("%s", op);
if(op[0] == ‘M‘) {
scanf("%d %d", &a, &b);
link(a, b);
}
else {
scanf("%d", &a);
find(a);
printf("%d\n", under[a]);
}
}
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-07 11:13:51