欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 明星 > 并查集—河工oj

并查集—河工oj

2025/11/4 9:47:58 来源:https://blog.csdn.net/2401_87338545/article/details/144299972  浏览:    关键词:并查集—河工oj

1304-连通块中点的个数

P1304 - 连通块中点的个数 - HAUEOJ

代码(用了关流不能用puts输出yes和no,会出错)

#include<bits/stdc++.h>
using namespace std;//连通块—并查集int n, m;
const int N = 1e5+10;
int p[N], cnt[N];void init() {for(int i = 1; i < N; i ++) p[i] = i, cnt[i] = 1;
} int find(int x) {if(p[x]!=x) p[x] = find(p[x]);return p[x];
}int main() {init();ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);//init();cin >> n >> m;while(m --) {string op;cin >> op;int a, b;if(op=="C") {cin >> a >> b;int pa = find(a), pb = find(b);if(pa==pb) continue;p[pa] = pb;cnt[pb] += cnt[pa];}else if(op=="Q2"){cin >> a;//int pa = find(a);//puts("1111111");cout << cnt[find(a)] << endl;}       else if(op=="Q1") {cin >> a >> b;int pa = find(a), pb = find(b);if(pa == pb) cout << "Yes" << endl;else cout << "No" << endl;}
//      else if(op=="Q2"){
//          cin >> a;
//          //int pa = find(a);
//          cout << cnt[find(a)] << endl;
//      }//op.clear();}return 0;
}

1306-关押罪犯

P1306 - 关押罪犯 - HAUEOJ

分析

b用于索引矛盾罪犯,来实现集合分离。

代码

#include<bits/stdc++.h>
using namespace std;// 两集合,并查集,集合合并 
int n, m;
const int N = 1e5+10;
int p[N], b[N]; struct crr {int x, y;int r;bool operator < (const crr &W) const {return r > W.r;}
}c[N];int find(int x) {if(x!=p[x]) p[x] = find(p[x]);return p[x];
}int main() {cin >> n >> m;for(int i = 1; i <= m; i ++) {int x, y, r;cin >> x >> y >> r;c[i].x = x, c[i].y = y, c[i].r = r;}sort(c+1,c+1+m);for(int i = 1; i <= n; i ++) p[i] = i;int maxx = 0;for(int i = 1; i <= m; i ++) {// 在一个监狱中的最大的边 if(find(c[i].x)==find(c[i].y)) {maxx = c[i].r;break;}if(!b[c[i].x]) b[c[i].x] = c[i].y;else {int _a = find(b[c[i].x]), _b = find(c[i].y);p[_a] = _b;} if(!b[c[i].y]) b[c[i].y] = c[i].x;else {int _a = find(b[c[i].y]), _b = find(c[i].x);p[_a] = _b;}}cout << maxx << endl;return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词