【发布时间】:2025-12-28 00:50:11
【问题描述】:
如果我有一个包含 1 个节点且没有边的图。连通分量的个数 = 1,对吧?
如果我有一个有 2 个节点且没有边的图。连通分量的个数 = 2,对吧?
如果我有一个包含 2 个节点和 1 个边的图。连通分量的个数 = 1,对吧?
我有这段代码:
typedef adjacency_list <vecS, vecS, undirectedS> Graph;
typedef graph_traits < Graph >::edge_descriptor Edge;
/* typedef graph_traits<Graph>::vertex_descriptor Vertex;
typedef property_map<Graph, vertex_index_t>::type IndexMap;
typedef std::pair<int,int> E;
typedef graph_traits<Graph>::vertex_iterator vertex_iter;
typedef graph_traits<Graph>::out_edge_iterator edge_iter;
typedef property_map<Graph, vertex_index_t>::type VertexIndexMap;
typedef property_map<Graph, edge_weight_t>::type EdgeWeightMap;*/
int main(int,char*[])
{
int num_nodes,num_edges;
cin >> num_nodes >> num_edges;
Graph g(num_nodes);
for(int i = 0;i < num_edges; i++) // i/p edges into graph g
{
int e1,e2;
cin >> e1 >> e2;
Edge e;
bool success;
tie(e,success) = add_edge(e1, e2, g);
}
vector <int> components(num_nodes);
int num = connected_components(g, &components[0]);
cout<<"moooooo"<<num<<endl;
对于这些输入:
1 0
和
2 0
和
2 1
我分别得到
1
和
2
和
2
为什么?现在不应该是1吗?我是否误解了连接组件?
我的程序为所有输入提供 num=2,我的输入如下:
4 3
1 2
2 3
3 4
4 4
1 2
2 3
3 4
4 1
5 5
1 2
2 3
3 4
4 1
3 5
6 6
1 2
2 3
3 4
4 1
3 5
5 6
8 9
1 2
2 3
3 4
4 1
3 5
5 6
6 7
7 8
8 5
8 10
1 2
2 3
3 4
4 1
3 5
5 6
6 7
7 8
8 5
4 6
我是做什么的?
【问题讨论】:
-
您确定要将
0和1放入e1和e2中吗?这就是连接两个顶点所需要的。 -
1 是顶点数,0 是边数,因为没有边,所以我不将任何东西放入图中。
-
1 和 0 -> 1 个顶点,0 个边,1 个连通分量(正确)。 2 和 0 -> 2 个顶点,0 个边,2 个连通分量(正确)。 2 和 1 -> 2 个顶点,1 条边,如果边在顶点 0 和顶点 1 之间(您需要在
cin >> e1 >> e2;中输入),那么将有 1 个连通分量,如果边不在他们获胜的那些顶点之间'未连接,将有 2 个组件。顶点从0开始并在num_vertices-1结束是重要的部分。 -
其实我只是想通了,完全正确。
标签: c++ boost connected-components