PAT A1013 Battle Over Cities [FIG traverse]

Title Description

link

M have given interconnecting roads between n cities, when deleting a city and its connecting roads, ask a few other remaining city at least the number of routes to be added in order to make them become re-connected graph

analysis

  • To better understand the meaning of the questions is to let you know the number of connected components block
  • Then it is how to calculate the numbers of the communication block: dfs! ! ! Be sure you brush ah
  • Processing the deletion of the city: \ (VIS [A] = to true \) ! ! ! !
#include <cstdio>
#include <algorithm>
using namespace std;
int v[1010][1010];
bool visit[1010];
int n;
void dfs(int node) {
    visit[node] = true;
    for(int i = 1; i <= n; i++) {
        if(visit[i] == false && v[node][i] == 1)
            dfs(i);
    }
}
int main() {
    int m, k, a, b;
    scanf("%d%d%d", &n, &m, &k);
    for(int i = 0; i < m; i++) {
        scanf("%d%d", &a, &b);
        v[a][b] = v[b][a] = 1;
    }
    for(int i = 0; i < k; i++) {
        fill(visit, visit + 1010, false);
        scanf("%d", &a);
        int cnt = 0;
        visit[a] = true;
        for(int j = 1; j <= n; j++) {
            if(visit[j] == false) {
                dfs(j);
                cnt++;
            }
        }
        printf("%d\n", cnt - 1);
    }
    return 0;
}

My code is to write complicated! ! !

#include<bits/stdc++.h>
using namespace std;

const int maxn = 1010;
bool G[maxn][maxn];
bool vis[maxn];
int n,m,k,st,ed,q;

void dfs(int p, int q){
    vis[p] = true;
    if(p == q) return;
    for(int i=1;i<=n;i++){
        if(i==q) continue;
        if(vis[i]==false && G[p][i]){
            dfs(i, q);
        }
    }
}

void solve(int q){
    int cnt = 0;
    memset(vis, 0, sizeof(vis));
    for(int i=1;i<=n;i++){
        if(vis[i]==false){
            dfs(i, q);
            cnt++;
        }
    }
    printf("%d\n", cnt-2);
}

int main(){
    cin>>n>>m>>k;
    memset(G,0,sizeof(G));
    for(int i=0;i<m;i++){
        cin>>st>>ed;
        G[st][ed] = G[ed][st] = 1;
    }
    for(int i=0;i<k;i++){
        cin>>q;
        solve(q);
    }


}

Guess you like

Origin www.cnblogs.com/doragd/p/11437887.html