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

时间: 2023-08-18 admin IT培训

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

畅通工程之最低成本建设问题(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;elsereturn 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;}elsecout<<ans<<endl;return 0;
}

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

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

输入格式:

输入的第一行给出城镇数目N (1<N≤1000)和候选道路数目M≤3N;随后的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