当前位置: 首页 > article >正文

并查集—河工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;
}


http://www.kler.cn/a/427658.html

相关文章:

  • 利用PHP和GD库实现图片切割
  • 项目五 李白个人生平
  • 可供参考的GitHub国内镜像
  • DApp浏览器能否集成在自己开发的DApp里?
  • 安全审计系统
  • Mac如何安装SVN
  • 扫描IP段内的使用的IP
  • 经典的CNN架构
  • 在玩“吃鸡”的时候游戏崩溃要如何解决?游戏运行时崩溃是什么原因?
  • k8s-Informer之Reflector的解析
  • 在Node.js局域网调试https的Vue项目
  • el-select的搜索功能
  • BOM模型
  • pytest中使用conftest做测试前置和参数化
  • 项目搭建:guice,jdbc,maven
  • 计算机网络 —— HTTPS 协议
  • 《ODIN: A Single Model for 2D and 3D Segmentation》CVPR2024
  • 《深入探索 Java JButton:功能与应用》
  • 机器学习详解(3):线性回归之代码详解
  • 电脑投屏到电脑:Windows,macOS及Linux系统可以相互投屏!