废话不多说直接上板子吧。
Prim
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 const int maxn=1001; 5 using namespace std; 6 7 int c,n,m; 8 int map[maxn][maxn]; 9 int dis[maxn]; 10 bool vis[maxn]; 11 12 int prim(){ 13 memset(dis,0x3f,sizeof(dis)); 14 memset(vis,0,sizeof(vis)); 15 int ans=0; 16 dis[1]=0; 17 while(1){ 18 int k=0; 19 for(int j=1;j<=n;j++){ 20 if(!vis[j]&&dis[j]<dis[k]) 21 k=j; 22 } 23 if(!k) break; 24 vis[k]=1; 25 ans+=dis[k]; 26 for(int j=1;j<=n;j++){ 27 if(dis[j]>map[k][j]){ 28 dis[j]=map[k][j]; 29 } 30 31 } 32 } 33 return ans; 34 } 35 int main(){ 36 37 while(cin>>c>>m>>n){ 38 int x,y,z; 39 memset(map,0x3f,sizeof(map)); 40 for(int i = 0; i < m; i++){ 41 cin>>x>>y>>z; 42 map[x][y]=map[y][x]=min(map[x][y],z); 43 } 44 int ans = prim(); 45 // cout<<ans<<endl; 46 if(ans > c || ans == 0){ 47 cout<<"No"<<endl; 48 } 49 else{ 50 cout<<"Yes"<<endl; 51 } 52 } 53 return 0; 54 }
Kruskal
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include<iostream> 2 #include<cstdio> 3 #include<string.h> 4 #include<algorithm> 5 #include<fstream> 6 using namespace std; 7 8 const int MAXN=505;//最大点数 9 const int MAXM=250005;//最大边数 10 int f[MAXN]; 11 12 struct Edge{ 13 int u,v,w; 14 }edge[MAXM]; 15 16 int cnt; 17 18 19 bool cmp(Edge a,Edge b){ 20 return a.w<b.w; 21 } 22 23 int find(int x){ 24 if(f[x] == -1) 25 return x; 26 else 27 return f[x] = find(f[x]); 28 } 29 30 int Kruskal(int n){ 31 memset(F,-1,sizeof(F)); 32 sort(edge,edge+cnt,cmp); 33 int cnt1 = 0;//计算加入的边数 34 int ans = 0; 35 for(int i = 0; i < cnt;i++){ 36 int u = edge[i].u; 37 int v = edge[i].v; 38 int w = edge[i].w; 39 int t1 = find(u); 40 int t2 = find(v); 41 if(t1 != t2){ 42 ans += w; 43 f[t1] = t2; 44 cnt1++; 45 } 46 if(cnt1 == n-1) 47 break; 48 } 49 if(cnt1 < n-1) 50 return -1;//不连通 51 else 52 return ans; 53 } 54 55 int main(){ 56 int c,n,m; 57 cin>>c>>m>>n; 58 cnt=0; 59 for(int i = 1; i <= m ;i++){ 60 int x,y,z; 61 cin>>x>>y>>z; 62 edge[cnt].u = x; 63 edge[cnt].v = y; 64 edge[cnt++].w = z; 65 } 66 int ans = Kruskal(n); 67 68 if(ans > c || ans == -1){ 69 cout<<"No"<<endl; 70 } 71 else{ 72 cout<<"Yes"<<endl; 73 } 74 75 return 0; 76 }