Description
求一个图的连通分量
Input
nnn 顶点数(nnn<=100100100)
边
Output
连通分量
Sample Input
8
6 3
1 2
2 5
5 4
4 1
8 7
0 0
Sample Output
4
思路
这里有五种方法,分别是dfs+邻接表,bfs+邻接表,dfs+邻接矩阵,bfs+邻接矩阵,bfs+邻接表+STL(队列)。dfs+邻接表,bfs+邻接表,dfs+邻接矩阵,bfs+邻接矩阵,bfs+邻接表+STL(队列)。dfs+邻接表,bfs+邻接表,dfs+邻接矩阵,bfs+邻接矩阵,bfs+邻接表+STL(队列)。
首先是两种读入:
邻接表
struct whw
{
int x,y;
}a[10001];
/*---------------------------------------------------------*/
scanf("%d%d",&x,&y);
while (x && y)
{
a[++m]=(whw){
y,h[x]};h[x]=m;
a[++m]=(whw){
x,h[y]};h[y]=m;//因为是无向图,所以x到y和y到x都要赋值
scanf("%d%d",&x,&y);
}
邻接矩阵
int h[1005][1005];
/*---------------------------------------------------------*/
scanf("%d%d",&x,&y);
while (x && y)
{
h[x][y]=h[y][x]=1;//上面
scanf("%d%d",&x,&y);
}
还有用STLSTLSTL时要注意:
库:<queue><queue><queue>
定义int类型的队列(wh):queue<int>wh;queue<int>wh;queue<int>wh;
还有用法:
(常见的)
用法 | 作用 |
---|---|