最近要学图论,所以写了一大堆关于图论的博客
题意:
给出无向图 G = ( V , E ) G=(V,E) G=(V,E)求最大联通分量。
其实这道题很水,轻轻松松就A了。
给出几种方法:
DFS+邻接矩阵
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
bool a[200][200],v[200];
int n,o;
void dfs(int i)
{
v[i]=1;
o++;
for(int j=1;j<=n;j++)
if(!v[j]&&a[i][j])dfs(j);
}
int main()
{
int b=1,c=1,d,s=0;
cin>>n;
while(b||c)
{
scanf("%d%d",&b,&c);
if(b||c) a[b][c]=a[c][b]=1;
}
for(int i=1;i<=n;i++)
if(!v[i]){o=0;dfs(i);s=max(s,o);}
cout<<s;
}
DFS+邻接表
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
struct a{
int next,to;
}a[200200];
bool v[200];
int n,o,tot,head[2000];
void add(int x,int y)
{
a[++tot].to=y;
a[tot].next=head[x];
head[x]=tot;
}
void dfs(int i)
{
v[i]=1;
o++;
for(int j=head[i];j;j=a[j].next)
if(!v[a[j].to])dfs(a[j].to);
}
int main()
{
int b=1,c=1,d,s=0;
cin>>n;
while(b||c)
{
scanf("%d%d",&b,&c);
if(b||c){
add(b,c);
add(c,b);
}
}
for(int i=1;i<=n;i++)
if(!v[i]){o=0;dfs(i);s=max(s,o);}
cout<<s;
}
BFS+邻接矩阵
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
bool a[200][200],v[200];
int n,o,que[200000];
void bfs(int i)
{
int h=0,tail=1;
v[i]=1;
o++;
que[1]=i;
while(h<tail)
{
h++;
for(int j=1;j<=n;j++)
if(!v[j]&&a[que[h]][j])
{
o++;
v[j]=1;
que[++tail]=j;
}
}
}
int main()
{
int b=1,c=1,d,s=0;
cin>>n;
while(b||c)
{
scanf("%d%d",&b,&c);
if(b||c) a[b][c]=a[c][b]=1;
}
for(int i=1;i<=n;i++)
if(!v[i]){o=0;bfs(i);s=max(s,o);}
cout<<s;
}
BFS+邻接表(唯一一次一次编译通过,果然还是这个较习惯)
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
struct a{
int next,to;
}a[200200];
bool v[200];
int n,o,tot,head[2000],que[200000];
void add(int x,int y)
{
a[++tot].to=y;
a[tot].next=head[x];
head[x]=tot;
}
void bfs(int i)
{
int h=0,tail=1;
v[i]=1;
o++;
que[1]=i;
while(h<tail)
{
h++;
for(int j=head[que[h]];j;j=a[j].next)
if(!v[a[j].to])
{
o++;
v[a[j].to]=1;
que[++tail]=a[j].to;
}
}
}
int main()
{
int b=1,c=1,d,s=0;
cin>>n;
while(b||c)
{
scanf("%d%d",&b,&c);
if(b||c){
add(b,c);
add(c,b);
}
}
for(int i=1;i<=n;i++)
if(!v[i]){o=0;bfs(i);s=max(s,o);}
cout<<s;
}
EX:STL queue
这里介绍几种常用函数:
push(i):插入元素i
front():取出当前队首元素
back():取出当前队尾元素
pop():弹出当前队首元素
empty():判断队列是否为空
代码
#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
using namespace std;
struct a{
int next,to;
}a[200200];
bool v[200];
int n,o,tot,head[2000];
void add(int x,int y)
{
a[++tot].to=y;
a[tot].next=head[x];
head[x]=tot;
}
void bfs(int i)
{
queue<int>que;
v[i]=1;
o++;
que.push(i);
while(!que.empty())
{
for(int j=head[que.front()];j;j=a[j].next)
if(!v[a[j].to])
{
o++;
v[a[j].to]=1;
que.push(a[j].to);
}
que.pop();
}
}
int main()
{
int b=1,c=1,d,s=0;
cin>>n;
while(b||c)
{
scanf("%d%d",&b,&c);
if(b||c){
add(b,c);
add(c,b);
}
}
for(int i=1;i<=n;i++)
if(!v[i]){o=0;bfs(i);s=max(s,o);}
cout<<s;
}