問題8.4:スムーズなプロジェクトの最低コストの建設問題(30ポイント)
特定の地域の都市交通状況を調査した後、既存の町間高速道路の統計を取得し、「ブロックされていないプロジェクト」の目標を提案しました。それは、地域全体の任意の2つの町間の迅速な輸送を可能にすることです(ただし、必ずしも直接ではありません)。 )高速道路は、高速道路を介して間接的に到達可能である限り、接続されています)。都市道路の統計表が利用可能になりました。この表は、高速道路に組み込まれる可能性のあるいくつかの道路のコストをリストし、スムーズなプロジェクトに必要な最低コストを求めています。
例:
#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;
}
アイデア:
プリムアルゴリズムを使用して、最小全域木を構築します。