我正在制作 ACM 竞赛的问题,以确定具有无向图 G 和属于每个组件的顶点的连接组件的数量。已经完成了 DFS 算法,计算了无向图的连接组件的数量(问题的难点),但我想不出任何东西来指示属于每个组件的节点或有节点的记录。
输入:第一行输入一个整数C,表示测试用例的个数。每个测试用例的第一行包含两个整数 N 和 E,其中 N 表示图中的节点数,E 表示图中的边数。然后沿着 E 行,每行有 2 个整数 I 和 J,其中 I 和 J 表示节点 I 和节点 J 之间存在一条边 (0 ≤ I, J
输出:在每个测试用例的第一行必须显示以下字符串“Case G: P component (s) connected (s)”,其中 G 表示测试用例的数量(从 1 开始),P 表示连接的组件数量在图中。然后是 X 行,每行包含属于连接组件的节点(按从小到大的顺序),由空格分隔。每个测试用例之后应该打印一个空行。输出应该写在“output.out”中。
例子:
输入:
2
6 9
0 1
0 2
1 2
5 4
3 1
2 4
2 5
3 4
3 5
8 7
0 1
2 1
2 0
3 4
4 5
5 3
7 6
输出:
Case 1: 1 component (s) connected (s)
0 1 2 3 4 5
Case 2: 3 component (s) connected (s)
0 1 2
3 4 5
6 7
这是我的代码:
#include <stdio.h>
#include <vector>
#include <stdlib.h>
#include <string.h>
using namespace std;
vector<int> adjacency[10000];
bool visited[10000];
/// @param Standard algorithm DFS
void dfs(int u){
visited[ u ] = true;
for( int v = 0 ; v < adjacency[u].size(); ++v ){
if( !visited[ adjacency[u][v] ] ){
dfs( adjacency[u][v] );
}
}
}
int main(int argc, char *argv []){
#ifndef ONLINE_JUDGE
#pragma warning(disable: 4996)
freopen("input.in", "r", stdin);
freopen("output.out", "w", stdout);
#endif
///enumerate vertices from 1 to vertex
int vertex, edges , originNode ,destinationNode, i, j,cont =1;
///number of test cases
int testCases;
int totalComponents;
scanf ("%d", &testCases);
for (i=0; i<testCases; i++){
memset( visited , 0 , sizeof( visited ) );
scanf("%d %d" , &vertex , &edges );
for (j=0; j<edges; j++){
scanf("%d %d" , &originNode ,&destinationNode );
adjacency[ originNode ].push_back( destinationNode );
adjacency[ destinationNode ].push_back( originNode );
}
totalComponents =0;
for( int i = 0 ; i < vertex ; ++i ){ // Loop through all possible vertex
if( !visited[ i ] ){ //if we have not visited any one component from that node
dfs( i ); //we travel from node i the entire graph is formed
totalComponents++; //increased amount of components
}
}
printf("Case %d: %d component (s) connected (s)\n" ,cont++, totalComponents);
for (j=0;j<total;j++){
/*here should indicate the vertices of each connected component*/
}
memset( adjacency , 0 , sizeof( adjacency ) );
}
return 0;
}
我对如何携带属于每个连接组件或结构的节点的内存应该用来存储,我应该如何修改我的代码来做到这一点有疑问?我想听听建议,想法或伪代码中的任何实现。谢谢大家