畅通工程之最低成本建设问题(30 分)

这个题目就是一个最小生成树,如果无法构成就输出impossible ,就是构成最小生成树的时候,每选择一条边然后加加,最后统计是否有n-1条就可以。

最小生成树的讲解在我的其他的博客中有提到

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <queue>
#include <math.h>
#include <stack>
#include <utility>
#include <string>
#include <sstream>
#include <cstdlib>
#include <set>
#define LL long long
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 3000 + 10;
int dir[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
int par[maxn];
bool vis[maxn][maxn];
int m,n;
struct Edge
{
    int w;
    int from;
    int next;
} edge[maxn];
bool cmp(const Edge a,const Edge b)
{
    return a.w < b.w;
}
void init(int n)
{
    for(int i = 0; i <= n; i++)
    {
        par[i] = i;
    }
    memset(vis,0,sizeof(vis));
}
int find1(int x)
{
    if(x == par[x])
        return x;
    else
        return par[x] = find1(par[x]);
}
int main()
{

    scanf("%d %d",&m,&n);
    init(m + 5);
    int a,b,c;
    for(int i = 0; i < n; i++)
    {
        cin>>a>>b>>c;
        edge[i].from = a;
        edge[i].next = b;
        edge[i].w = c;
    }
    sort(edge,edge+n,cmp);
    int ans = 0;
        int cnt = 0;
    for(int i = 0; i < n; i++)
    {
        int x = find1(edge[i].from);
        int y = find1(edge[i].next);
        if(x != y)
        {
            par[x] = y;
            ans += edge[i].w;
        }
    }
    for(int i = 1;i <= m;i++)
	{
		if(par[i] != i)
		{
			cnt++;
		}
	}
	if(cnt != m - 1)
	{
		cout<<"Impossible"<<endl;
	}
	else
    cout<<ans<<endl;
    return 0;
}

7-2 畅通工程之最低成本建设问题(30 分)

某地区经过对城镇交通状况的调查,得到现有城镇间快速道路的统计数据,并提出“畅通工程”的目标:使整个地区任何两个城镇间都可以实现快速交通(但不一定有直接的快速道路相连,只要互相间接通过快速路可达即可)。现得到城镇道路统计表,表中列出了有可能建设成快速路的若干条道路的成本,求畅通工程需要的最低成本。

输入格式:

输入的第一行给出城镇数目N (1<N1000)和候选道路数目M3N;随后的M行,每行给出3个正整数,分别是该条道路直接连通的两个城镇的编号(从1编号到N)以及该道路改建的预算成本。

输出格式:

输出畅通工程需要的最低成本。如果输入数据不足以保证畅通,则输出“Impossible”。

输入样例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

输出样例1:

12

输入样例2:

5 4
1 2 1
2 3 2
3 1 3
4 5 4

输出样例2:

Impossible

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值