Карта сайта Kansoftware
НОВОСТИУСЛУГИРЕШЕНИЯКОНТАКТЫ
Разработка программного обеспечения

Boost Graph Library: Incremental Connected Components

Boost , ,

Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

C++ Boost

Incremental Connected Components

This section describes a family of functions and classes that work together to calculate the connected components of an undirected graph. The algorithm used here is based on the disjoint-sets (fast union-find) data structure [8,27] which is a good method to use for situations where the graph is growing (edges are being added) and the connected components information needs to be updated repeatedly. This method does not cover the situation where edges are both added and removed from the graph, hence it is called incremental[42] (and not fully dynamic). The disjoint-sets class is described in Section Disjoint Sets.

The following five operations are the primary functions that you will use to calculate and maintain the connected components. The objects used here are a graph g, a disjoint-sets structure ds, and vertices u and v.

  • initialize_incremental_components(g, ds)
    Basic initialization of the disjoint-sets structure. Each vertex in the graph g is in its own set.
  • incremental_components(g, ds)
    The connected components are calculated based on the edges in the graph g and the information is embedded in ds.
  • ds.find_set(v)
    Extracts the component information for vertex v from the disjoint-sets.
  • ds.union_set(u, v)
    Update the disjoint-sets structure when edge (u,v) is added to the graph.

Complexity

The time complexity for the whole process is O(V + E alpha(E,V)) where E is the total number of edges in the graph (by the end of the process) and V is the number of vertices. alpha is the inverse of Ackermann's function which has explosive recursively exponential growth. Therefore its inverse function grows very slowly. For all practical purposes alpha(m,n) <= 4 which means the time complexity is only slightly larger than O(V + E).

Example

Maintain the connected components of a graph while adding edges using the disjoint-sets data structure. The full source code for this example can be found in examples/incremental_components.cpp.

using namespace boost;
int main(int argc, char* argv[]) 
{
  typedef adjacency_list  Graph;
  typedef graph_traits::vertex_descriptor Vertex;
  typedef graph_traits::vertices_size_type VertexIndex;
  const int VERTEX_COUNT = 6;
  Graph graph(VERTEX_COUNT);
  std::vector rank(num_vertices(graph));
  std::vector parent(num_vertices(graph));
  typedef VertexIndex* Rank;
  typedef Vertex* Parent;
  disjoint_sets ds(&rank[0], &parent[0]);
  initialize_incremental_components(graph, ds);
  incremental_components(graph, ds);
  graph_traits::edge_descriptor edge;
  bool flag;
  boost::tie(edge, flag) = add_edge(0, 1, graph);
  ds.union_set(0,1);
  boost::tie(edge, flag) = add_edge(1, 4, graph);
  ds.union_set(1,4);
  boost::tie(edge, flag) = add_edge(4, 0, graph);
  ds.union_set(4,0);
  boost::tie(edge, flag) = add_edge(2, 5, graph);
  ds.union_set(2,5);
    
  std::cout << "An undirected graph:" << std::endl;
  print_graph(graph, get(boost::vertex_index, graph));
  std::cout << std::endl;
    
  BOOST_FOREACH(Vertex current_vertex, vertices(graph)) {
    std::cout << "representative[" << current_vertex << "] = " <<
      ds.find_set(current_vertex) << std::endl;
  }
  std::cout << std::endl;
  typedef component_index Components;
  // NOTE: Because we're using vecS for the graph type, we're
  // effectively using identity_property_map for a vertex index map.
  // If we were to use listS instead, the index map would need to be
  // explicity passed to the component_index constructor.
  Components components(parent.begin(), parent.end());
  // Iterate through the component indices
  BOOST_FOREACH(VertexIndex current_index, components) {
    std::cout << "component " << current_index << " contains: ";
    // Iterate through the child vertex indices for [current_index]
    BOOST_FOREACH(VertexIndex child_index,
                  components[current_index]) {
      std::cout << child_index << " ";
    }
    std::cout << std::endl;
  }
  return (0);
}


initialize_incremental_components

Graphs: undirected
Properties: rank, parent (in disjoint-sets)
Complexity:

template <class VertexListGraph, class DisjointSets> 
void initialize_incremental_components(VertexListGraph& G, DisjointSets& ds)

This prepares the disjoint-sets data structure for the incremental connected components algorithm by making each vertex in the graph a member of its own component (or set).

Where Defined

boost/graph/incremental_components.hpp


incremental_components

Graphs: undirected
Properties: rank, parent (in disjoint-sets)
Complexity: O(E)

template <class EdgeListGraph, class DisjointSets>
void incremental_components(EdgeListGraph& g, DisjointSets& ds)

This function calculates the connected components of the graph, embedding the results in the disjoint-sets data structure.

Where Defined

boost/graph/incremental_components.hpp

Requirements on Types


same_component

Properties: rank, parent (in disjoint-sets)
Complexity: O(alpha(E,V))

template <class Vertex, class DisjointSet>
bool same_component(Vertex u, Vertex v, DisjointSet& ds)

This function determines whether u and v are in the same component.

Where Defined

boost/graph/incremental_components.hpp

Requirements on Types

  • Vertex must be compatible with the rank and parent property maps of the DisjointSets data structure.


component_index

component_index<Index>

The component_index class provides an STL container-like view for the components of the graph. Each component is a container-like object, and access is provided via the operator[]. A component_index object is initialized with the parents property in the disjoint-sets calculated from the incremental_components() function. Optionally, a vertex -> index property map is passed in (identity_property_map is used by default).

Where Defined

boost/graph/incremental_components.hpp

Members

Member Description
value_type/size_type Тип индекса компонентов (то же, что и индекс).
size_type size() Возвращает количество компонентов в графе.
итератор/const_iterator Итераторы, используемые для обхода доступных индексов компонентов [0 доразмера().
итератор начинает() конст Возвращает итератор в начале индексов компонентов (0).
конец итератора Возвращает итератор в начале индексов компонентов (0).
std::pairoperator[size_type index] const Возвращает итератор в начале индексов компонентов (0).


Copyright © 2000-2001Джереми Сик, Университет Индианыjsiek@osl.iu.edu]
Ли-Куан Ли, Университет Индианыllee@cs.indiana.edu]
Эндрю Лумсдейн, Университет Индианыlums@osl.iu.edu

Статья Boost Graph Library: Incremental Connected Components раздела может быть полезна для разработчиков на c++ и boost.




Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта.



:: Главная :: ::


реклама


©KANSoftWare (разработка программного обеспечения, создание программ, создание интерактивных сайтов), 2007
Top.Mail.Ru

Время компиляции файла: 2024-08-30 11:47:00
2025-05-21 10:15:22/0.0063369274139404/0