目录
1. 修路
题目 : http://oj.daimayuan.top/course/7/problem/546
思想: 需要修的路即为有多少个连通块,然后减一
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 5e5+5;
const int inf = 0x3f3f3f3f;
const int P = 9999971;
int n,m;
int f[N];
int findset(int x){
if(f[x]==x){
return x;
}
return findset(f[x]);
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin>>n>>m;
for(int i=1;i<=n;i++){
f[i]=i;
}
for(int i=1;i<=m;i++){
int x,y;
cin>>x>>y;
int fx=findset(x),fy=findset(y);
if(fx==fy){
continue;
}
f[fx]=fy;
}
int cnt=0;
for(int i=1;i<=n;i++){
if(f[i]==i){
cnt++;
}
}
cout<<cnt-1<<"\n";
return 0;
}
2. 修复公路(带扩展域的并查集)
3.https://www.luogu.com.cn/problem/P1111
思路:
当合并一次之后,我们扫一遍fa数组,统计fa[i]=i的个数:
- 如果只有1个fa[i]=i,就说明所有的全部联通了(因为只有1个人是自己的祖先,别的人都跟着他)
- 如果不止1个,就说明当前没有全部联通(因为两个人互相没有关系),需要继续合并。
代码:
// Problem: A - 修复公路
// Contest: Virtual Judge - 2023暑期训练-高级数据结构 Part1
// URL: https://vjudge.net/contest/571187#problem/A
// Memory Limit: 128 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2e5+5;
int n,m;
int f[N];
int num;
int ans;
struct node{
int a,b,t;
}e[N];
bool cmp(node x,node y){
return x.t<y.t;
}
int find(int x){
if(x!=f[x]) return find(f[x]);
return f[x];
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
f[i]=i;
}
for(int i=1;i<=m;i++){
cin>>e[i].a>>e[i].b>>e[i].t;
}
sort(e+1,e+1+m,cmp);
for(int i=1;i<=m;i++){
int x=find(e[i].a),y=find(e[i].b);
if(x==y) continue;
f[x]=y;
num++;
ans=e[i].t;
}
if(num!=n-1) cout<<"-1\n";
else cout<<ans<<"\n";
return 0;
}
3. 食物链(带边权的并查集)
https://www.luogu.com.cn/problem/P2024
思路:
代码:
// Problem: E - 食物链
// Contest: Virtual Judge - 2023暑期训练-高级数据结构 Part1
// URL: https://vjudge.net/contest/571187#problem/E
// Memory Limit: 128 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2e5+5;
int n,m;
int p[N];
int d[N];
int find(int x){
if(x!=p[x]){
int u=p[x];
p[x]=find(p[x]);
d[x]+=d[u];
}
return p[x];
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
p[i]=i;
}
int res=0;
for(int i=1;i<=m;i++){
int t,x,y;
cin>>t>>x>>y;
if(x>n||y>n) res++;
else{
int px=find(x),py=find(y);
if(t==1){
if(px==py&&(d[x]-d[y])%3){
res++;
}
else if(px!=py){
p[px]=py;
d[px]=d[y]-d[x];
}
}
else{
if(px==py&&(d[x]-d[y]-1)%3){
res++;
}
else if(px!=py){
p[px]=py;
d[px]=d[y]+1-d[x];
}
}
}
}
cout<<res<<"\n";
return 0;
}
代码源: 带权并查集 http://oj.daimayuan.top/course/15/problem/719