图的联通分量个数统计(判断图是否联通)

题目链接:https://pintia.cn/problem-sets/994805046380707840/problems/994805063963230208

基本上是裸的,直接看代码吧

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const int inf=1<<30;
 5 const double pi=acos(-1);
 6 const int mod=998244353;
 7 const int maxn=510;
 8 const int maxm=6300;
 9 int e[maxn][maxn];int n,m,cnt;
10 int vis[maxn];
11 void dfs(int x){
12     vis[x]=1;
13     for(int i=0;i<n;i++){
14         if(!vis[i]&&e[x][i]){
15             dfs(i);
16         }
17     }
18 }
19 int count(){
20     int cnt=0;
21     memset(vis,0,sizeof(vis));
22     for(int i=0;i<n;i++){
23         if(!vis[i]){
24             cnt++;
25             dfs(i);
26         }
27     }
28     return cnt;
29 }
30 int main(){
31     scanf("%d%d",&n,&m);
32     int x,y;
33     for(int i=0;i<m;i++){
34         scanf("%d%d",&x,&y);
35         e[x][y]=e[y][x]=1;    
36     }
37     cnt=count();
38     int k;scanf("%d",&k);
39     for(int i=0;i<k;i++){
40         scanf("%d",&x);
41         for(int i=0;i<n;i++){
42             if(e[x][i]){
43                 e[x][i]=e[i][x]=0;
44             }
45         }
46         int now=count();
47         if(now-cnt>1){
48             printf("Red Alert: City %d is lost!\n",x);
49         }else{
50             printf("City %d is lost.\n",x);
51         }cnt=now;
52         if(i==n-1) {
53             printf("Game Over.\n");break;
54         }        
55     }
56     return 0;
57 }

 

图的联通分量个数统计(判断图是否联通)

上一篇:移动端开发ios和安卓兼容问题


下一篇:Appium