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

来源:互联网 发布:网络舆情监控 宣传部 编辑:程序博客网 时间:2024/04/29 07:50

这个题目就是一个最小生成树,如果无法构成就输出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 longusing 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 151 2 51 3 31 4 71 5 41 6 22 3 42 4 62 5 22 6 63 4 63 5 13 6 14 5 104 6 85 6 3

输出样例1:

12

输入样例2:

5 41 2 12 3 23 1 34 5 4

输出样例2:

Impossible

阅读全文
1 0