7-12 畅通工程之最低成本建设问题(30 point(s)) 【PRIME】

7-12 畅通工程之最低成本建设问题(30 point(s))

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

输入的第一行给出城镇数目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

思路

每次从 现有的点 中 寻找一根 最短路径 到达 一个 未访问过的点

然后每一步操作 加上其 权值

最后 如果 入队的点 不够 N 的话 就是 不可以

AC代码

#include <cstdio>
#include <cstring>
#include <ctype.h>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <map>
#include <stack>
#include <set>
#include <numeric>
#include <sstream>
#include <iomanip>
#include <limits>

#define CLR(a) memset(a, 0, sizeof(a))
#define pb push_back

using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef pair<string, int> psi;
typedef pair<string, string> pss;

const double PI = 3.14159265358979323846264338327;
const double E = exp(1);
const double eps = 1e-30;

const int INF = 0x3f3f3f3f;
const int maxn = 1e3 + 5;
const int MOD = 1e9 + 7;

int G[maxn][maxn];
int lowCost[maxn];

int n, m;

int findMin()
{
    int Min = INF;
    int flag = 0;
    for (int i = 1; i <= n; i++)
    {
        if (lowCost[i] && lowCost[i] < Min)
        {
            Min = lowCost[i];
            flag = i;
        }
    }
    return flag;
}

int prime()
{
    int ans = 0;
    for (int i = 1; i <= n; i++)
        lowCost[i] = G[1][i];
    lowCost[1] = 0;
    for (int i = 2; i <= n; i++)
    {
        int k = findMin();
        if (k)
        {
            ans += lowCost[k];
            lowCost[k] = 0;
            for (int j = 1; j <= n; j++)
            {
                if (lowCost[j] && G[k][j] < lowCost[j])
                    lowCost[j] = G[k][j];
            }
        }
        else
            return -1;
    }
    return ans;
}


int main()
{
    memset(G, 0x3f, sizeof(G));
    scanf("%d%d", &n, &m);
    for (int i = 0; i < n; i++)
        G[i][i] = 0;
    int x, y, v;
    for (int i = 0; i < m; i++)
    {
        scanf("%d%d%d", &x, &y, &v);
        G[x][y] = G[y][x] = v;
    }
    int ans = prime();
    if (ans == -1)
        printf("Impossible
");
    else
        cout << ans << endl;
}






原文地址:https://www.cnblogs.com/Dup4/p/9433179.html