首页 技术 正文
技术 2022年11月9日
0 收藏 312 点赞 3,596 浏览 1810 个字
//prim算法
#include<cstdio>
#include<cmath>
#include<cstring>
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<string>
#include<stack>
#include<queue>
#include<map>
#define MAX 510
const int INF=1000000000;
using namespace std;
//顶点到集合s的最短距离
int d[MAX],G[MAX][MAX];
int n,m;
bool isVisit[MAX]={false};
//返回最小生成树的边权之和
int prim(){
fill(d,d+MAX,INF);
d[0]=0;
int ans=0;
for(int i=0;i<n;i++){
int u=-1,MIN=INF;
for(int j=0;j<n;j++){
if(isVisit[j]==false&&d[j]<MIN){
u=j;
MIN=d[j];
}
}
if(u==-1) return -1;
isVisit[u]=true;
ans+=d[u];
for(int v=0;v<n;v++){
if(isVisit[v]==false&&G[u][v]!=INF&&G[u][v]<d[v])
d[v]=G[u][v];
}
}
return ans;
}int main(){
int u,v,w;
//顶点个数,边数
scanf("%d%d",&n,&m);
//初始化图
fill(G[0],G[0]+MAX*MAX,INF);
for(int i=0;i<m;i++){
scanf("%d%d%d",&u,&v,&w);
G[u][v]=G[v][u]=w;
}
int ans=prim();
printf("%d\n",ans);
return 0;
}

  类似Dijkstra算法,但是此时d[]表示顶点Vi与集合S的最短距离

kruskal算法:

运用并查集,判断两个点是否在一个及集合中,,即测试两个端点是否在不同连通块中

#include<cstdio>
#include<cmath>
#include<cstring>
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<string>
#include<stack>
#include<queue>
#include<map>
const int MAX=;
const int MAXE=;
const int INF=;
using namespace std;
//顶点到集合s的最短距离
int d[MAX],father[MAX];
int n,m;
bool isVisit[MAX]={false};
struct edge{
int node1,node2;
int weight;
}E[MAXE];
bool cmp(edge e1,edge e2){
return e1.weight<e2.weight;
}
int findFather(int x){
int a=x;
while(x!=father[x]){
x=father[x];
}
while(a!=father[a]){
int temp=a;
a=father[a];
father[temp]=x;
}
return x;
}
int kruskal(){
int ans=,num_edge=;
for(int i=;i<n;i++)
father[i]=i;
sort(E,E+m,cmp);
for(int i=;i<m;i++){
int f1=findFather(E[i].node1);
int f2=findFather(E[i].node2);
if(f1!=f2){
father[f1]=f2;
ans+=E[i].weight;
num_edge++;
//边数等于顶点数-1结束
if(num_edge==n-) break;
}
}
if(num_edge!=n-) return -;
else return ans;
}int main(){
//顶点个数,边数
scanf("%d%d",&n,&m);
for(int i=;i<m;i++){
scanf("%d%d%d",&E[i].node1,&E[i].node2,&E[i].weight);
}
int ans=kruskal();
printf("%d\n",ans);
return ;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,490
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,905
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,738
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,491
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,129
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,292