数据结构——畅通工程之最低成本建设问题

 

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

 这道题,与畅通工程这道题的思想基本一致同样是使用畅通工程中使用的两种算法,只是增加了一个impossible的限制,这个时候我们就需要对算法进行一定得摸索了解,使其能适合我们的题目。

在畅通工程的代码中,我们利用used数组来记录是否将全部的点储存完毕,那么这个时候我们同样可以用used数组,来判断是否所有的点均全部进行了连接,如果不是就输出impossible.

 

下面给出AC代码:

#include <bits/stdc++.h>

using namespace std;
const int maxn=1000+10;
const int INF=0x3f3f3f3f;


int cost[maxn][maxn];
int mincost[maxn];
bool used[maxn];
int V,E;

void prim()
{
    memset(mincost,INF,sizeof(mincost));
    memset(used,false,sizeof(used));

    mincost[1]=0;
    int res=0;
    bool flag=false;

    while(true)
    {
        int v=-1;
        //cout<<"ggV:   "<<V<<endl;
        for(int u=1;u<=V;u++)
        {
            //cout<<"gg:    "<<mincost[u]<<"   "<<used[u]<<endl;
            if(!used[u]&&(v==-1||mincost[u]<mincost[v]))
            {
                v=u;
            }
        }

        //cout<<"ggv:    "<<v<<endl;
        if(v==-1) break;

        used[v]=true;
        if(mincost[v]==INF)
        {
            flag=true;
            break;
        }
        res+=mincost[v];

        for(int u=1;u<=V;u++)
        {
            mincost[u]=min(mincost[u],cost[u][v]);
        }
    }

    if(flag) printf("Impossible\n");
    else printf("%d\n",res);
}

int main()
{
    for(int i=0;i<maxn;i++) memset(cost[i],INF,sizeof(cost[i]));
    //for(int i=0;i<maxn;i++) cout<<"gg::   "<<cost[i][1]<<endl;

    scanf("%d %d",&V,&E);
    for(int i=0;i<E;i++)
    {
        int s,t,c; scanf("%d %d %d",&s,&t,&c);
        cost[s][t]=c;
        cost[t][s]=c;
        //cout<<"输出中间值   "<<s<<"  "<<t<<"   "<<c<<"    "<<f<<endl;
    }
    prim();
    return 0;
}

 

    原文作者:道路修建问题
    原文地址: https://blog.csdn.net/NCC__dapeng/article/details/84314746
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞