浙大版《数据结构(第2版)》题目集-习题8.4

习题8.4 畅通工程之最低成本建设问题 (30point(s))

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

Example:

#include <iostream>
#include <climits>
#include <vector>
#include <list>

using namespace std;

typedef int Vertex;
struct Edge {
    Vertex adj;
    int cost;
};

int main()
{
    int N, M;
    cin >> N >> M;
    vector<list<Edge>> Graph(N+1);
    for(int i = 0; i < M; i++) {
        Vertex src, dst;
        int cost;
        cin >> src >> dst >> cost;
        auto next = Graph[src].begin();
        for(; next != Graph[src].end(); next++) {
            if(cost <= next->cost) break;
        }
        Graph[src].insert(next, {dst,cost});
        next = Graph[dst].begin();
        for(; next != Graph[dst].end(); next++) {
            if(cost <= next->cost) break;
        }
        Graph[dst].insert(next, {src,cost});
    }

    vector<bool> Visited(N+1);
    Visited[1] = true;
    int Cost = 0;
    for(int i = 0; i < N-1; i++) {
        Vertex Adj = 0;
        int Min = INT_MAX;
        for(Vertex src = 1; src <= N; src++) {
            if(Visited[src]) {
                auto x = Graph[src].begin();
                for(; x != Graph[src].end(); x++) {
                    if(Visited[x->adj]) {
                        x = Graph[src].erase(x);
                        --x;
                    } else break;
                }
                if(x != Graph[src].end()) {
                    if (Min > x->cost) {
                        Min = x->cost;
                        Adj = x->adj;
                    }
                }
            }
        }
        if(Adj == 0) {
            cout << "Impossible" << endl;
            return 0;
        }
        Cost += Min;
        Visited[Adj] = true;
    }
    cout << Cost << endl;
    return 0;
}

思路:

使用普利姆(Prim)算法,构造最小生成树。

猜你喜欢

转载自blog.csdn.net/u012571715/article/details/113481080