PAT(甲级) 1013 Battle Over Cities (25point(s))

本文介绍了一种算法,用于计算在给定连通图中删除特定顶点后形成的连通分量的数量。通过使用邻接矩阵和邻接表两种不同的数据结构,文章详细解释了如何进行深度优先搜索(DFS),并提供了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

题目链接

思路

这道题大意是给你一个连通图,删去某一点后,求有几个连通分量;
用邻接矩阵法存储图,因为删去城市有K种可能,所以要循环K次;
每次循环时都要依次dfs检查每个城市,看这个城市与哪个城市相连,共循环N ^ 2次

知识点

二维vector的初始化方法;
在Java中用户不能调用构造方法,总是用new通过系统调用,所以不会出现类型()直接初始化的方法;
但c++允许直接调用构造方法,所以有vector(size,value)的方法出现;

代码
#include <iostream>
#include <vector>
using namespace std;

vector<vector<int>> v(1010, vector<int>(1010,0));//图的邻接矩阵
bool check[1010];
int N = 0;//总的城市数量

//深度优先递归访问每个城市
void dfs(int node){
    check[node] = true;
    for(int i=1; i<=N; i++){
    //如果这个城市没有访问过,并且与一个城市相连,则访问另一个城市
        if(check[i]==false && v[node][i]==1){
            dfs(i);
        }
    }
}

int main(){
    int M, K;
    scanf("%d%d%d", &N, &M, &K);
    for(int i=0; i<M; ++i){
        int a, b;
        scanf("%d%d",&a, &b);
        v[a][b] = v[b][a] = 1;
    }
    
    for(int i=0; i<K; ++i){
        fill(check, check+1010, false);
        int a = 0, cnt = 0;
        scanf("%d", &a);
        check[a] = true;
        for(int j=1; j<=N; ++j){
            //如果没有访问过,就递归访问
            if(check[j] == false){
                dfs(j);
                ++cnt;
            }
        }
        printf("%d\n",cnt-1);
    }
    
    return 0;
}
邻接表版
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#include <cstring>
#include <string>
#include <math.h>
using namespace std;
const int maxn = 1010;
vector<vector<int>> graph;
bool isVisit[maxn];
int n, m, k;
//每次DFS前都要判断这个元素有没有被看过
void DFS(int root){
     isVisit[root] = true;//标记已被看过
     for(int i = 0; i < graph[root].size(); i ++){
          if(isVisit[graph[root][i]] == false){
              DFS(graph[root][i]);
          }
     }
     return;
}

int main()
{
     int a, b, c;
     scanf("%d%d%d", &n, &m, &k);
     graph.resize(n + 1);
     for(int i = 0; i < m; i ++){
          scanf("%d%d", &a, &b);
          graph[a].push_back(b);
          graph[b].push_back(a);
     }
     for(int i = 0; i < k; i ++){
          scanf("%d", &c);
          int ans = 0;
          fill(isVisit, isVisit + n + 1, false);
          isVisit[c] = true;
          for(int j = 1; j <= n; j ++){
               if(isVisit[j] == false){
                    DFS(j);
                    ans ++;
               }
          }
          printf("%d\n", ans - 1);
     }
     system("pause");
     return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值