公路村村通(最小生成树)

5-10 公路村村通   (30分)

现有村落间道路的统计数据表中,列出了有可能建设成标准公路的若干条道路的成本,求使每个村落都有公路连通所需要的最低成本。

输入格式:

输入数据包括城镇数目正整数NN(\le 1000≤1000)和候选道路数目MM(\le 3N≤3N);随后的MM行对应MM条道路,每行给出3个正整数,分别是该条道路直接连通的两个城镇的编号以及该道路改建的预算成本。为简单起见,城镇从1到NN编号。

输出格式:

输出村村通需要的最低成本。如果输入数据不足以保证畅通,则输出-1−1,表示需要建设更多公路。

输入样例:

6 15
1 2 5
1 3 3
1 4 7
1 5 4
1 6 2
2 3 4
2 4 6
2 5 2
2 6 6
3 4 6
3 5 1
3 6 1
4 5 10
4 6 8
5 6 3

输出样例:

12


prim算法:
 
#include <iostream> #include <cstdio> #include <cmath> #include <queue> #include <stack> #include <map> #include <algorithm> #include <vector> #include <string> #define INF 100000000 using namespace std; int n,m; struct edge { int to; int cost; edge(int x,int y) { to=x; cost=y; } }; typedef struct edge edge; vector<edge> G[1005]; int lowcost[1005]; int vis[1005]; int solve() { int ans=0; int k=1; for(int i=1;i<=n;i++) { lowcost[i]=INF; vis[i]=0; } vis[k]=1; lowcost[k]=0; for(int i=1;i<n;i++) { for(int j=0;j<G[k].size();j++) { int v=G[k][j].to; int cost=G[k][j].cost; if(lowcost[v]>cost && vis[v]==0) { lowcost[v]=cost; } } int minn=INF; for(int j=1;j<=n;j++) { if(lowcost[j]<=minn && vis[j]==0) { minn=lowcost[j]; k=j; } } vis[k]=1; ans+=lowcost[k]; } return ans; } int main() { scanf("%d%d",&n,&m); for(int i=0;i<m;i++) { int x,y,z; scanf("%d%d%d",&x,&y,&z); edge tmp(y,z); G[x].push_back(tmp); edge temp(x,z); G[y].push_back(temp); } int ans=solve(); if(ans>=INF) ans=-1; printf("%d\n",ans); return 0; } 

Kruskal算法:

 
#include <iostream> #include <cstdio> #include <cmath> #include <queue> #include <stack> #include <map> #include <algorithm> #include <vector> #include <string> #define INF 100000000 using namespace std; int n,m; struct edge { int x,y,cost; }; typedef struct edge edge; edge a[3005]; int fa[1005]; int cmp(edge x,edge y) { return x.cost<y.cost; } int Find(int x) { if(fa[x]==x) return x; return fa[x]=Find(fa[x]); } int solve() { int ans=0; int cnt=0; sort(a,a+m,cmp); for(int i=0;i<m;i++) { int x=a[i].x; int y=a[i].y; int cost=a[i].cost; int xx=Find(x); int yy=Find(y); if(xx!=yy) { cnt++; fa[xx]=yy; ans+=cost; } if(cnt==n-1) { break; } } if(cnt!=n-1) return -1; return ans; } int main() { scanf("%d%d",&n,&m); for(int i=0;i<m;i++) { scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].cost); } for(int i=1;i<=n;i++) { fa[i]=i; } int ans=solve(); printf("%d\n",ans); return 0; } 


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值