连通子图的个数来判断有多少无法连通的区域,当失去一座城市的时候,如果连通子图的个数增加大于1,则整个国家的连通性被改变,增加数为0(单独的一个城市,本身不和其他任何城市相连)或1(边缘城市,和子图之间只有一条通路)说明没有改变连通性
#include <iostream> #include <stdlib.h> using namespace std; int **e; bool *city; int n, m, k; void dfs(int a) { city[a] = true; for(int i=0; i<n; i++) { if(city[i]==false&&e[i][a]==1) { dfs(i); } } } int countcnt() { int cnt = 0; fill(city, city+n, false); for(int i=0; i<n; i++) { if(city[i]==false) { dfs(i); cnt++; } } return cnt; } int main() { cin >> n >> m; e = (int **)malloc(sizeof(int*)*(n+1)); for(int i=0; i<n+1; i++) e[i] = (int*)malloc(sizeof(int)*(n+1)); city = (bool *)malloc(sizeof(bool)*(n+1)); for(int i=0; i<n+1; i++) for(int j=0; j>n+1; j++) e[i][j]=0; int temp1, temp2; for(int i=0; i<m; i++) { cin >> temp1 >> temp2; e[temp1][temp2] = e[temp2][temp1]= 1; } cin >> k; int cnt = countcnt(); for(int i=0; i<k; i++) { cin >> temp1; for(int j=0; j<n; j++) { e[temp1][j] = 0; e[j][temp1] = 0; } int tempcnt = countcnt(); if(tempcnt<=cnt+1) cout << "City " << temp1 << " is lost.\n"; else { cout << "Red Alert: City " << temp1 << " is lost!\n"; } if(i==n-1) { cout << "Game Over.\n"; } cnt = tempcnt; } return 0; }