【并查集】LA3644 X-Plosives
n个元素的集合应用问题——并查集。
题目大意
装车,把一些两个元素组成的化合物按输入次序往车上装,如果会发生爆炸(存在k个简单化合物,正好包含k种元素),记录,输出不能装车的化合物总数。
说一下思路
怎样理解“存在k个简单化合物,正好包含k种元素”?
每个化合物在顶点处分摊到1/2个元素,成环!根节点相同!问题都是等价的!
想一想并查集的查找和合并操作,在合并过程中计数那些根节点相同的边就可以了~
参考代码
#include<bits/stdc++.h>
using namespace std;
const int _max = 1e5 + 10;
int a,b,pre[_max],ans;
void init(){//每个点所在的集合初始化为自身
for(int i = 1;i <= _max;++ i) pre[i] = i;
}
int find(int x){//查找,返回元素x的根节点
return pre[x] == x? x : pre[x]=find(pre[x]);
}
void join(int a,int b){//合并
int x = find(a),y = find(b);
if(x != y) pre[x] = y;
else ans++; //加上(a,b)则成环,会发生爆炸booooom!
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
#endif // ONLINE_JUDGE
while(scanf("%d",&a) == 1){
init();
ans = 0;
while(a != -1){
scanf("%d",&b);
join(a,b);
scanf("%d",&a);
}
printf("%d\n",ans);
}
return 0;
}
- 加粗
Ctrl + B
- 斜体
Ctrl + I
- 引用
Ctrl + Q
- 插入链接
Ctrl + L
- 插入代码
Ctrl + K
- 插入图片
Ctrl + G
- 提升标题
Ctrl + H
- 有序列表
Ctrl + O
- 无序列表
Ctrl + U
- 横线
Ctrl + R
- 撤销
Ctrl + Z
- 重做
Ctrl + Y
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-07-30 04:14:07