我正在制作ACM竞赛的问题,以确定具有无向图G和属于每个组件的顶点的连通组件的数量。已经完成了DFS算法,计算了无向图的连接组件的数量(问题的难点),但我想不出任何东西来指示属于每个组件的节点或者有一个记录的节点
输入: 输入的第一行是整数C,表示测试用例的数量。每个测试用例的第一行包含两个整数N和E,其中N表示图中的节点数,E表示其中的边数。然后遵循E行,每行有2个整数I和J,其中I和J表示节点I和节点J之间存在边(0≤I,J
输出: 在每个测试用例的第一行中,必须显示以下字符串"案例G:连接的P个组件( 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;
}
我怀疑如何携带属于每个连接组件或结构的节点的内存应该用于存储,我应该如何修改我的代码来执行此操作?,我想听听建议,想法或任何实现伪代码。感谢所有
答案 0 :(得分:2)
算法大致是:
结果是一组“组件”数据结构(在我的实现中为std::vector
),每个都包含一组专门互连的节点。
考虑:
std::vector
来有效地构建此结构。这是工作代码。请注意,使用了一些C ++ 11功能,但如果使用较旧的编译器,它们应该很容易替换。错误处理留给读者练习。
#include <iostream>
#include <vector>
#include <algorithm>
// A set of inter-connected nodes.
typedef std::vector<unsigned> Component;
// Graph node.
struct Node {
Node() : Traversed(false) {
}
std::vector<unsigned> Children;
std::vector<unsigned> Parents;
bool Traversed;
};
// Recursive portion of the FindGraphComponents implementation.
// graph: The graph constructed in FindGraphComponents().
// node_id: The index of the current element of graph.
// component: Will receive nodes that comprise the current component.
static void FindConnectedNodes(std::vector<Node>& graph, unsigned node_id, Component& component) {
Node& node = graph[node_id];
if (!node.Traversed) {
node.Traversed = true;
component.push_back(node_id);
for (auto i = node.Children.begin(); i != node.Children.end(); ++i)
FindConnectedNodes(graph, *i, component);
for (auto i = node.Parents.begin(); i != node.Parents.end(); ++i)
FindConnectedNodes(graph, *i, component);
}
}
// Finds self-connected sub-graphs (i.e. "components") on already-prepared graph.
std::vector<Component> FindGraphComponents(std::vector<Node>& graph) {
std::vector<Component> components;
for (unsigned node_id = 0; node_id < graph.size(); ++node_id) {
if (!graph[node_id].Traversed) {
components.push_back(Component());
FindConnectedNodes(graph, node_id, components.back());
}
}
return components;
}
// Finds self-connected sub-graphs (i.e. "components") on graph that should be read from the input stream.
// in: The input test case.
std::vector<Component> FindGraphComponents(std::istream& in) {
unsigned node_count, edge_count;
std::cin >> node_count >> edge_count;
// First build the structure that can be traversed recursively in an efficient way.
std::vector<Node> graph(node_count); // Index in this vector corresponds to node ID.
for (unsigned i = 0; i < edge_count; ++i) {
unsigned from, to;
in >> from >> to;
graph[from].Children.push_back(to);
graph[to].Parents.push_back(from);
}
return FindGraphComponents(graph);
}
void main() {
size_t test_case_count;
std::cin >> test_case_count;
for (size_t test_case_i = 1; test_case_i <= test_case_count; ++test_case_i) {
auto components = FindGraphComponents(std::cin);
// Sort components by descending size and print them.
std::sort(
components.begin(),
components.end(),
[] (const Component& a, const Component& b) { return a.size() > b.size(); }
);
std::cout << "Case " << test_case_i << ": " << components.size() << " component (s) connected (s)" << std::endl;
for (auto components_i = components.begin(); components_i != components.end(); ++components_i) {
for (auto edge_i = components_i->begin(); edge_i != components_i->end(); ++edge_i)
std::cout << *edge_i << ' ';
std::cout << std::endl;
}
std::cout << std::endl;
}
}
将此计划称为......
GraphComponents.exe < input.in > output.out
...其中input.in
包含您问题中描述的格式的数据,它将在output.out
中生成所需的结果。
答案 1 :(得分:1)
解决方案要容易得多,你必须声明两个大小为顶点数的数组
int vertexNodes [vertex] / / / array to store the nodes
int vertexComponents [vertex] / / / array to store the number of components
然后,当你调用DFS时,每个顶点都存储在顶点数组中,并存储在该组件所属
for( int i = 0 ; i < vertex ; ++i ) //iterate on all vertices
{
vertexNodes [i]=i; //fill the array with the vertices of the graph
if( !visited[ i ] )
{ ///If any node is visited DFS call
dfs(i);
totalComponents++; ///increment number of components
}
vertexComponents [i]=totalComponents; ///is stored at each node component belongs to
}
最后,它打印总组件并创建一个标志,其中第一个组件的值与每个顶点的组件进行比较
printf("Case %d: %d component (s) connected (s)\n" ,cont++, totalComponents);
int flag = vertexComponents[0]; ///Create a flag with the value of the first component
for (k=0; k <totalComponents; ++k) ///do a cycle length of the number of components
{
if (flag == vertexComponents [k] ) ///check if the vertex belongs to the first component
{
printf ("%d ", vertexComponents[k]); ///print on the same line as belonging to the same component
}else {
printf ("\n"); ///else we make newline and update the flag to the next component
flag = vertexComponents[k];
printf ("%d ", vertexComponents[k]);///and print the vertices of the new connected component
}
}
答案 2 :(得分:0)
您可以像这样存储组件:
typedef vector<int> Component;
vector<Component> components;
并修改代码:
void dfs(int u){
components.back().push_back(u);
visited[ u ] = true;
for( int v = 0 ; v < adjacency[u].size(); ++v ){
if( !visited[ adjacency[u][v] ] ){
dfs( adjacency[u][v] );
}
}
}
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
components.push_back(Component());
dfs( i ); //we travel from node i the entire graph is formed
}
}
现在totalComponents是components.size():
printf("Case %d: %d component (s) connected (s)\n" ,cont++, components.size());
for (j=0;j<components.size();j++){
Component& component = components[j];
std::sort(component.begin(), component.end());
for(int k=0; k<component.size(); k++) {
printf("%d ", component[k]);
}
printf("\n");
}
components.clear();
请注意,代码未经过测试。包含<algorithm>
以获取排序功能。
答案 3 :(得分:0)
测试2个节点是否连接的通用算法:
首先,您的节点将分别位于其集合中,
o o1 o o o o o o2
\ / \ / \ / \ /
o o o o o o o o
\ / \ /
o o o o o o o o
\ /
o o1 o o o o o o2
随着算法的进展和合并,它的输入相对减半。
在上面的例子中,我想看看o1和o2之间是否有路径。我在合并所有边之后才发现这条路径。某些图形可能具有单独的组件(断开连接),这使得您无法在最后设置一个组件。在这种情况下,您可以使用此算法测试连通性,甚至可以计算图表中组件的数量。组件数是算法完成时能够获得的集合数。
可能的图表(对于上面的树):
o-o1-o-o-o2
| |
o o
|
o