Description
求一个图的连通分量
Input
n 顶点数(<=100)
边
Output
连通分量
Sample Input
8
6 3
1 2
2 5
5 4
4 1
8 7
0 0
Sample Output
4
解题思路
忘了是无向图,只存了一条边,一开始深深迷惑了1个h。。。:)
老师布置了5个方法:
- DFS+邻接矩阵
- BFS+邻接矩阵
- DFS+邻接表
- BFS+邻接表
- BFS+邻接表(STL)
DFS+邻接矩阵
#include<iostream>
#include<cstdio>
using namespace std;
int a[200][200],v[200],n,s,Gun;
void dfs(int x){
v[x]=1;
for(int y=1;y<=n;y++){
if(a[x][y]&&!v[y]){
++s;
dfs(y);
}
}
}
int main(){
scanf("%d",&n);
int x,y;
scanf("%d%d",&x,&y);
while(x){
a[x][y]=1;
a[y][x]=1;//邻接矩阵
scanf("%d%d",&x,&y);
}
for(int i=1;i<=n;i++){
if(!v[i]){//标记这个点遍历过没
s=1;
dfs(i);
Gun=max(Gun,s);
}
}
printf("%d",Gun);
}
BFS+邻接矩阵
#include<iostream>
#include<cstdio>
using namespace std;
int a[200][200],v[200],n,Gun,h,t;
void bfs(int x){
int f[200]={0,x};v[x]=1;
h=0,t=1;
while(h++<t){//写题以来最简单的BFS
for(int y=1;y<=n;y++){
if(a[f[h]][y]&&!v[y]){
v[y]=1;
f[++t]=y;
}
}
}
}
int main(){//水到不想写注释
scanf("%d",&n);
int x,y;
scanf("%d%d",&x,&y);
while(x){
a[x][y]=1;
a[y][x]=1;
scanf("%d%d",&x,&y);
}
for(int i=1;i<=n;i++){
if(!v[i]){
bfs(i);
Gun=max(Gun,t);
}
}
printf("%d",Gun);
}
DFS+邻接表
#include<iostream>
#include<cstdio>
using namespace std;
struct DT{
int to,next;
}e[40010];
int head[200],n,num,s,Gun,v[200];
void DFS(int x){
v[x]=1;
for(int i=head[x];i;i=e[i].next){//不停跳过去
if(!v[e[i].to]){
++s;
DFS(e[i].to);
}
}
}
int main(){
scanf("%d",&n);
int x,y;
scanf("%d%d",&x,&y);
while(x){
e[++num].to=y,e[num].next=head[x],head[x]=num;
e[++num].to=x,e[num].next=head[y],head[y]=num;//邻接表
scanf("%d%d",&x,&y);
}
for(int i=1;i<=n;i++){
if(!v[i]){
s=1;
DFS(i);
Gun=max(Gun,s);
}
}
printf("%d",Gun);
}
BFS+邻接表
#include<iostream>
#include<cstdio>
using namespace std;
struct DT{
int to,next;
}e[40010];
int head[200],n,num,Gun,v[200],h,t;
void BFS(int x){
int f[20010]={0,x};
h=0,t=1,v[x]=1;
while(h++<t){
for(int i=head[f[h]];i;i=e[i].next)//把f[h]打成h的我微笑面对生活
if(!v[e[i].to]){
v[e[i].to]=1;
f[++t]=e[i].to;
}
}
}
int main(){
scanf("%d",&n);
int x,y;
scanf("%d%d",&x,&y);
while(x){
e[++num].to=y,e[num].next=head[x],head[x]=num;
e[++num].to=x,e[num].next=head[y],head[y]=num;
scanf("%d%d",&x,&y);
}
for(int i=1;i<=n;i++){
if(!v[i]){
BFS(i);
Gun=max(Gun,t);
}
}
printf("%d",Gun);
}
BFS+邻接表(STL)
不知道STL的队列的同志,麻烦度娘接待一下
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
struct DT{
int to,next;
}e[40010];
int head[200],n,num,Gun,v[200],t;
queue<int> f;
void BFS(int x){
f.push(x);
v[x]=1,t=1;
while(!f.empty()){
for(int i=head[f.front()];i;i=e[i].next)
if(!v[e[i].to]){
v[e[i].to]=1;
++t;
f.push(e[i].to);
}
f.pop();
}
}
int main(){
scanf("%d",&n);
int x,y;
scanf("%d%d",&x,&y);
while(x){
e[++num].to=y,e[num].next=head[x],head[x]=num;
e[++num].to=x,e[num].next=head[y],head[y]=num;
scanf("%d%d",&x,&y);
}
for(int i=1;i<=n;i++){
if(!v[i]){
BFS(i);
Gun=max(Gun,t);
}
}
printf("%d",Gun);
}