L2-013. 红色警报

来源:互联网 发布:软件流程图模板 编辑:程序博客网 时间:2024/06/11 11:26

本题要求:

战争中保持各个城市间的连通性非常重要。本题要求你编写一个报警程序,当失去一个城市导致国家被分裂为多个无法连通的区域时,就发出红色警报。注意:若该国本来就不完全连通,是分裂的k个区域,而失去一个城市并不改变其他城市之间的连通性,则不要发出警报。

输入格式:

输入在第一行给出两个整数N0 < N <=500)和M(<=5000),分别为城市个数(于是默认城市从0N-1编号)和连接两城市的通路条数。随后M行,每行给出一条通路所连接的两个城市的编号,其间以1个空格分隔。在城市信息之后给出被攻占的信息,即一个正整数K和随后的K个被攻占的城市的编号。注意:输入保证给出的被攻占的城市编号都是合法的且无重复,但并不保证给出的通路没有重复。

输出格式:

对每个被攻占的城市,如果它会改变整个国家的连通性,则输出“Red Alert: City k is lost!”,其中k是该城市的编号;否则只输出“City k is lost.”即可。如果该国失去了最后一个城市,则增加一行输出“Game Over.”。

输入样例:

5 40 11 33 00 451 2 0 4 3

输出样例:

City 1 is lost.City 2 is lost.Red Alert: City 0 is lost!City 4 is lost.City 3 is lost.Game Over.

解题思路 :

运用深度搜索进行结点统计区域数,类似于POJ上河塘的题。

代码 :

#include<iostream>#include<queue>#include<string>#include<cstring>#include<algorithm>using namespace std;int map[501][501] = {0};int n;bool isV[501];bool isLost[501];void getArea(int id) {    if (id < 0 || id >= n || isV[id] || isLost[id]) {        return;    }    isV[id] = true;    for (int i = 0; i < n; i++) {        if (map[id][i] == 1) {            getArea(i);        }    }}int getArea() {    int num = 0;    for (int i = 0; i < n; i++) {        if (!isV[i] && !isLost[i]) {            getArea(i);            num++;        }    }    return num;}int main(){    memset(isLost, false, sizeof(isLost));    cin >> n;    int m;    cin >> m;        for (int i = 0; i < m; i++) {        int x, y;        cin >> x >> y;        map[x][y] = 1;        map[y][x] = 1;    }    cin >> m;    memset(isV, false, sizeof(isV));    int area = getArea();    for (int i = 0; i < m; i++) {        int id;        cin >> id;        for (int j = 0; j < n; j++) {            map[id][j] = 0;            map[j][id] = 0;        }        isLost[id] = true;        memset(isV, false, sizeof(isV));        int temp = getArea();        if (area < temp) {            area = temp;            cout << "Red Alert: City " << id << " is lost!" << endl;        } else {            area = temp;            cout << "City " << id << " is lost." << endl;        }        if (temp == 0) {            cout << "Game Over." << endl;        }    }     return 0;}
0 0
原创粉丝点击