BFS
#define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
#include<bits/stdc++.h>
using namespace std;
int N,M,K;
const int maxn = 1010;
const int INF = 1000000;
int G[maxn][maxn];
int wu;
void BFS(int &liantong,int u,bool isvisited[])
{
if (!isvisited[u])
{
liantong++;
isvisited[u] = true;
queue<int> q;
q.push(u);
while (!q.empty())
{
int topel = q.front();
q.pop();
for (int v = 1; v <= N; v++)
{
if (v!=wu&&!isvisited[v] && G[topel][v] != INF)
{
isvisited[v] = true;
q.push(v);
}
}
}
}
}
int main()
{
scanf("%d %d %d", &N, &M,&K);
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= N; j++)
{
G[i][j] = INF;
}
}
for (int i = 0; i < M; i++)
{
int a,b;
scanf("%d %d", &a,&b);
G[a][b] = 1;
G[b][a] = 1;
}
for (int i = 0; i < K; i++)
{
scanf("%d", &wu);
int liantong = 0;
bool isvisited[maxn] = { false };
for (int j = 1; j <= N; j++)
{
if(j!=wu)
BFS(liantong,j,isvisited);
}
if (i != 0)
printf("\n");
printf("%d", liantong-1);
}
return 0;
}
并查集
没有路径压缩时
#define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
#include<bits/stdc++.h>
using namespace std;
int N,M,K;
const int maxn = 1010;
int father[maxn] ;
int findfather(int x)
{
while (x != father[x])
{
x = father[x];
}
return x;
}
void Union(int a, int b)
{
int fa=findfather(a);
int fb=findfather(b);
father[fa] = fb;
}
int main()
{
scanf("%d %d %d", &N, &M,&K);
vector<int>a;
vector<int>b;
for (int i = 0; i < M; i++)
{
int n1, n2;
scanf("%d %d", &n1, &n2);
a.push_back(n1);
b.push_back(n2);
}
for (int i = 0; i < K; i++)
{
bool flag[maxn] = { 0 };
for (int i = 0; i < maxn; i++)
{
father[i] = i;
}
int wu;
scanf("%d", &wu);
for (int j = 0; j < M; j++)
{
if (a[j] != wu&&b[j]!=wu)
{
Union(a[j], b[j]);
}
}
for (int i = 1; i <= N; i++)
{
if (i != wu)
{
int fa = findfather(i);
flag[fa] = true;
}
}
int block = 0;
for (int i = 1; i <= N; i++)
{
block += flag[i];
}
if (i != 0)
printf("\n");
printf("%d", block - 1);
}
return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
#include<bits/stdc++.h>
using namespace std;
int N,M,K;
const int maxn = 1010;
int father[maxn] ;
int findfather(int x)
{
int a = x;
while (x != father[x])
{
x = father[x];
}
while (a != father[a])
{
int z = a;
a = father[a];
father[z] = x;
}
return x;
}
void Union(int a, int b)
{
int fa=findfather(a);
int fb=findfather(b);
father[fa] = fb;
}
int main()
{
scanf("%d %d %d", &N, &M,&K);
vector<int>a;
vector<int>b;
for (int i = 0; i < M; i++)
{
int n1, n2;
scanf("%d %d", &n1, &n2);
a.push_back(n1);
b.push_back(n2);
}
for (int i = 0; i < K; i++)
{
bool flag[maxn] = { 0 };
for (int i = 0; i < maxn; i++)
{
father[i] = i;
}
int wu;
scanf("%d", &wu);
for (int j = 0; j < M; j++)
{
if (a[j] != wu&&b[j]!=wu)
{
Union(a[j], b[j]);
}
}
for (int i = 1; i <= N; i++)
{
if (i != wu)
{
int fa = findfather(i);
flag[fa] = true;
}
}
int block = 0;
for (int i = 1; i <= N; i++)
{
block += flag[i];
}
if (i != 0)
printf("\n");
printf("%d", block - 1);
}
return 0;
}