5

無向グラフGと各コンポーネントに属する頂点を持つ連結成分の数を決定するためにACM競合の問題を作成しています。すでにDFSアルゴリズムを使用して、無向グラフの連結成分の数を数えていますが(問題の難しい部分)、各成分に属するノードを示したり、ノードの記録を持ったりすることは考えられません。

入力:入力の最初の行は、テストケースの数を示す整数Cになります。各テストケースの最初の行には、2つの整数NとEが含まれています。ここで、Nはグラフ内のノードの数を表し、Eはグラフ内のエッジの数を表します。次に、それぞれ2つの整数IとJを持つE線をたどります。ここで、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;
    }

接続された各コンポーネントまたは構造に属するノードのメモリをどのように運ぶか、保存に使用する必要があるか、これを行うためにコードをどのように変更する必要があるかについて疑問があります。提案、アイデア、または擬似コードでの実装を聞きたいです。ありがとうございます

4

4 に答える 4

2

アルゴリズムは大まかに次のとおりです。

  • グラフノードを取得します。
  • 直接または間接的に(両方向に)接続されているすべてのノードを検索します。
  • それらすべてを「トラバース」としてマークし、新しいコンポーネントに配置します。
  • トラバースされていない次のノードを見つけて、プロセスを繰り返します。

その結果、一連の「コンポーネント」データ構造(std::vector私の実装ではs)が作成され、それぞれに相互接続されたノードのセットが含まれます。

考慮事項:

  • 「下」(親から子へ)と「上」(子から親へ)の両方を効率的にトラバースし、接続されているすべてのノード(両方向)を再帰的に見つけてノードをマークできる構造にグラフを格納する必要があります。私たちが行くにつれて「横断」したように。ノードは整数の連続範囲で識別されるため、ランダムアクセスプロパティを使用するだけでこの構造を効率的に構築できます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

于 2011-11-01T13:31:38.563 に答える
1

解決策ははるかに簡単です。頂点の数のサイズの2つの配列を宣言する必要があります

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
                }
            }
于 2011-11-01T15:01:55.527 に答える
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>ソート関数を取得するためにインクルードします。

于 2011-11-01T02:49:59.683 に答える
0

2つのノードが接続されているかどうかをテストするための一般的なアルゴリズム:

  1. グラフ全体をエッジに分割します。各エッジをセットに追加します。
  2. 次の反復で、手順2で作成したエッジの2つの外側ノードの間にエッジを描画します。これは、元のエッジの元のセットに新しいノード(対応するセットを含む)を追加することを意味します。(基本的にはマージを設定します)
  3. 探している2つのノードが同じセットになるまで、2を繰り返します。また、手順1の後にチェックを行う必要があります(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の間にパスがあるかどうかを確認していました。このパスは、すべてのエッジをマージした後の最後でのみ見つかりました。一部のグラフには、個別のコンポーネント(切断されている)が含まれている場合があります。これにより、最後に1つのセットを設定できなくなります。このような場合、このアルゴリズムを使用して連結性をテストし、グラフ内のコンポーネントの数を数えることもできます。コンポーネントの数は、アルゴリズムが終了したときに取得できるセットの数です。

可能なグラフ(上のツリーの場合):

o-o1-o-o-o2
  |    |
  o    o
       |
       o
于 2011-12-17T03:10:22.710 に答える