Zhejiang University Edition "Data Structure (Second Edition)" Question Collection-Exercise 8.5

Exercise 8.5 The local minimum cost problem of smooth engineering (35point(s))

After surveying urban traffic conditions in a certain area, statistics on existing inter-town express roads were obtained, and the goal of "Unblocked Project" was put forward: to enable rapid transportation between any two towns in the entire area (but not necessarily direct). Express roads are connected, as long as they are indirectly reachable via express roads). A statistical table of urban roads is now available. The table lists the cost of building an expressway between any two towns and whether the road has been completed. Now please write a program to calculate the minimum cost required for smooth traffic in the entire region.

Example:

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

using namespace std;

struct Edge {
    int src;
    int dst;
    int cost;
};

vector<int> com;
vector<bool> visited;
int component;

void DFS(vector<list<Edge>> &G, int v)
{
    if(visited[v]) return ;
    visited[v] = true;
    com[v] = component;
    for(auto &x : G[v]) {
        DFS(G, x.dst);
    } 
}

int main()
{
    int N;
    cin >> N;
    list<Edge> edge;
    vector<list<Edge>> adj(N+1);
    for(int i = 0; i < N*(N-1)/2; i++) {
        int src, dst, cost, build;
        cin >> src >> dst >> cost >> build;
        if(build == 1) {
            adj[src].push_back({src, dst, cost});
            adj[dst].push_back({dst, src, cost});
        } else {
            auto next = edge.begin();
            for(; next != edge.end(); next++) {
                if(cost <= next->cost) break;
            }
            edge.insert(next, {src, dst, cost});
        }
    }
    com.resize(N+1);
    visited.resize(N+1);
    for(int i = 1; i <= N; i++) {
        if(!visited[i]) {
            ++component;
            DFS(adj, i);
        }
    }
    int cost = 0;
    if(component > 1) {
        for(auto &x: edge) {
            if(com[x.src] != com[x.dst]) {
                cost += x.cost;
                int Max = max(com[x.src], com[x.dst]);
                int Min = min(com[x.src], com[x.dst]);
                for(auto &y : com) {
                    if(y == Max) y = Min;
                }
            }
        }
    }
    cout << cost << endl;
    return 0;
}

Ideas:

  1. The sides without roads are queued in ascending order
  2. Calculate connected components
  3. Connect different connected components according to the edges to be built in ascending order.

Guess you like

Origin blog.csdn.net/u012571715/article/details/113483764