并查集板子加例题
//http://poj.org/problem?id=1611
#include<bits/stdc++.h>
using namespace std;
const int maxn = 30010;
int f[maxn],num[maxn],n,m;
int find(int x) {return f[x] == x ? x : f[x] = find(f[x]);
}
int main() {while(cin >> n >> m && (n + m)) {for(int i = 0; i < n; i++) {f[i] = i;num[i] = 1;}while(m--) {int k, t;cin >> k >> t;int ft = find(t);while(--k) {int i;cin >> i;int fi = find(i);if(ft != fi) {f[fi] = ft;num[ft] += num[fi];}}}cout << num[find(0)] <<endl;}return 0;
}
//http://acm.hdu.edu.cn/showproblem.php?pid=1272
#include<bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int f[maxn], flag, visit[maxn];
void init() {for(int i = 0; i< maxn; i++)f[i] = i, visit[i] = 0;
}
int find(int x) {return f[x] == x ? x : f[x] = find(f[x]);
}
void Union(int x,int y) {int fx = find(x);int fy = find(y);if(fx == fy) flag = 0;else f[fx] = fy;
}
int main() {//freopen("D:\\MY\\ce.txt","r",stdin);init();int a,b;flag = 1;while(cin >> a >> b) {visit[a] = 1, visit[b] = 1;if(a == -1 && b == -1)break;if(a == 0 && b == 0) {int sum = 0;for(int i = 1; i < maxn; i++) {if(visit[i] && f[i] == i)sum ++;if(sum >= 2) {flag = 0;break;}}if(flag) cout << "Yes" <<endl;else cout << "No" <<endl;init();flag = 1;continue;}Union(a, b);}return 0;
}
//https://ac.nowcoder.com/acm/contest/1080/B
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
int f[maxn],n,ans[maxn];
void init() {for(int i = 0; i < n; i++)f[i] = i;
}
int find(int x) {return f[x] == x ? x : f[x] = find(f[x]);
}
int main() {cin >> n;init();int t = n, temp;while(t--) {cin >> temp;int ft = find(temp % n);ans[ft] = temp;f[ft] = find((ft + 1) % n);}for(int i = 0; i < n; i++)cout << ans[i] << " ";cout << endl;return 0;
}
//https://codeforces.com/problemset/problem/1131/F
#include<bits/stdc++.h>
using namespace std;
const int maxn = 150010;
int f[maxn],n,l[maxn],r[maxn],ans[maxn];
void init() {for(int i = 1; i <= n; i++)f[i] = l[i] = r[i] = i, ans[i] = 0;
}
int find(int x) {return x == f[x] ? x : f[x] = find(f[x]);
}
int main() {int a,b;cin >> n;init();while(--n) {cin >> a >>b;int fa = find(a);int fb = find(b);if(fa != fb) {ans[r[fa]] = l[fb];f[fa] = fb;l[fb] = l[fa];}}for(int i = l[find(1)]; i; i = ans[i])cout << i << " ";cout <<endl;return 0;
}
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現金大獎
總結
- 上一篇: 羊骨汤的功效与作用、禁忌和食用方法
- 下一篇: 独脚金太子参煲瘦肉的功效与作用、禁忌和食