最小生成树总结
什么是最小生成树
给定一个无向图,求图中的一些边使得删去其他边改图仍然联通且这些边边权之和最小。这就是最小生成树。
至于为什么是树,要让图联通的最少边数只能是节点数
怎么求最小生成树
这需要用到并查集。先将所有边按边权从小到大排序,在依次遍历。
如果该边为有效边(可以使连通块数量
例题
P3366 【模板】最小生成树
模板题,没什么好说的。
#include<iostream>
#include<algorithm>
using namespace std;
int n , m , a[5005] , cnt , ans;
struct node{
int x , y , len;
}c[200005];
bool cmp(node A , node B){
return A.len < B.len;
}
int find(int x){
if(a[x]==x)return x;
return a[x] = find(a[x]);
}
int main(){
cin >> n >> m;
for(int i=1;i<=n;i++)a[i] = i;
for(int i=1;i<=m;i++){
cin >> c[i].x >> c[i].y >> c[i].len;
}
sort(c+1,c+m+1,cmp);
for(int i=1;i<=m&&cnt<(n-1);i++){
int fx = find(c[i].x) , fy = find(c[i].y);
if(fx!=fy)cnt++ , ans += c[i].len , a[fx] = fy;
}
if(cnt==(n-1))cout << ans;
else cout << "orz";
return 0;
}
P2847 [USACO16DEC] Moocast G
这道题需要自己创造路径,即每两头奶牛之间都有一条路径,从中选出
注意数组的大小,要开到
#include<cmath>
#include<iostream>
#include<algorithm>
#define int long long
using namespace std;
struct node{
int x , y , len;
}a[1000005];
int n , x[1005] , y[1005] , m , f[1005] , ans;
bool cmp(node A , node B){
return A.len < B.len;
}
int find(int x){
if(f[x]==x)return x;
return f[x] = find(f[x]);
}
signed main(){
cin >> n;
for(int i=1;i<=n;i++)cin >> x[i] >> y[i] , f[i] = i;
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
a[++m] = {i,j,(x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j])};
}
}
sort(a+1,a+m+1,cmp);
for(int i=1;i<=m;i++){
int fx = find(a[i].x) , fy = find(a[i].y);
if(fx!=fy)f[fx] = fy , ans = max(a[i].len,ans);
}
cout << ans;
return 0;
}
P1340 兽径管理
板子+多组数据
#include<iostream>
#include<algorithm>
using namespace std;
int n , a[5005] , cnt , ans , w;
struct node{
int x , y , len;
}c[200005];
bool cmp(node A , node B){
return A.len < B.len;
}
int find(int x){
if(a[x]==x)return x;
return a[x] = find(a[x]);
}
int main(){
cin >> n >> w;
for(int m=1;m<=w;m++){
for(int i=1;i<=n;i++)a[i] = i;
cin >> c[m].x >> c[m].y >> c[m].len;
cnt = 0 , ans = 0;
stable_sort(c+1,c+m+1,cmp);
for(int i=1;i<=m&&cnt<(n-1);i++){
int fx = find(c[i].x) , fy = find(c[i].y);
if(fx!=fy)cnt++ , ans += c[i].len , a[fx] = fy;
}
if(cnt==(n-1))cout << ans;
else cout << "-1";
cout << "\n";
}
return 0;
}