1013 Battle Over Cities (25 point(s))

1013 Battle Over Cities (25 point(s))

It is vitally important to have all the cities connected by highways in a war. If a city is occupied by the enemy, all the highways from/toward that city are closed. We must know immediately if we need to repair any other highways to keep the rest of the cities connected. Given the map of cities which have all the remaining highways marked, you are supposed to tell the number of highways need to be repaired, quickly.

For example, if we have 3 cities and 2 highways connecting city​1​​-city​2​​ and city​1​​-city​3​​. Then if city​1​​ is occupied by the enemy, we must have 1 highway repaired, that is the highway city​2​​-city​3​​.

Example:

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

using namespace std;

typedef int Vertex;
struct Graph {
    int Nv;
    int Ne;
    vector<list<Vertex>> G;
};

void DFS(Graph &G, Vertex v, vector<bool> &Visited)
{
    for(auto &x : G.G[v])
        if(!Visited[x]) {
            Visited[x] = true;
            DFS(G, x, Visited);
        }
}

int Repair(Graph &G, int city)
{
    vector<bool> Visited(G.Nv+1, false);
    Visited[city] = true;
    int component = 0;
    for(int i = 1; i <= G.Nv; i++) {
        if(Visited[i]) continue;    
        component++;
        DFS(G, i, Visited);
    }
    return max(component-1, 0);
}

int main()
{
    Graph G;
    int N, M, K;
    cin >> N >> M >> K;
    G.Nv = N;
    G.Ne = M;
    G.G.resize(N+1);
    for(int i = 0; i < M; i++) {
        int c1, c2;
        cin >> c1 >> c2;
        G.G[c1].push_back(c2);
        G.G[c2].push_back(c1);
    }
    for(int i = 0; i < K; i++) {
        int city;
        cin >> city;
        cout << Repair(G, city) << endl;
    }
}

思路:

利用DFS,计算连通分量的数量,需要的铁路数量是该值-1

猜你喜欢

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