战争中的城市
https://www.acwing.com/problem/content/1487/
并查集维护连通块的写法
#include <iostream>
#include <cstring>
using namespace std;
const int N = 1010, M = 500010;
int n, m, k;
int p[N];
struct Edge
{
int a, b;
}e[M];
int find(int x)
{
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
int main()
{
scanf("%d%d%d", &n, &m, &k);
for (int i = 0; i < m; i ++ ) scanf("%d%d", &e[i].a, &e[i].b);
while (k -- )
{
int x;
scanf("%d", &x);
for (int i = 1; i <= n; i ++ ) p[i] = i;
int cnt = n - 1;
for (int i = 0; i < m; i ++ )
{
int a = e[i].a, b = e[i].b;
if (a != x && b != x)
{
int pa = find(a), pb = find(b);
if (pa != pb)
{
p[pa] = pb;
cnt -- ;
}
}
}
printf("%d\n", cnt - 1);
}
return 0;
}
dfs维护连通块的写法
#include <iostream>
#include <vector>
#include <memory.h>
using namespace std;
const int N = 1010;
vector<int> graph[N];
int vis[N];
int lost,ans;
int n,m,k;
int a,b;
void dfs(int x){
vis[x]=1;
int size = graph[x].size();
for(int i =0;i < size;i++){
int p = graph[x][i];
if(vis[p]==0 && p!=lost){
dfs(p);
}
}
}
void solve(){
ans =0;
memset(vis,0,sizeof vis);
for(int i = 1;i<=n;i++){
if(i!=lost && vis[i] ==0){
ans++; dfs(i);
}
}
printf("%d\n",ans-1);
return ;
}
int main(){
scanf("%d%d%d",&n,&m,&k);
for(int i = 1; i <= m;i++){
scanf("%d%d",&a,&b);
graph[a].push_back(b);
graph[b].push_back(a);
}
for(int i =1;i<=k;i++){
scanf("%d",&lost);
solve();
}
return 0;
}