【发布时间】:2016-02-19 17:40:13
【问题描述】:
用户输入顶点的数量 (n),然后 - 在接下来的 n 行中 - 顶点是如何连接的,即数量 x第 i 行中的 表示顶点 i 与顶点 x 相连(图是无向的)。任务是在此图中找到连接组件的数量,而我的代码 - 由于某种原因我无法找到 - 输出错误值(例如,输入 4 2 1 2 4 ,我的代码输出 4 而不是 2)。非常感谢任何帮助。
#include <iostream>
#include <vector>
#include <stack>
int n;
using namespace std;
vector <int> graph[1000006];
int components[1000006];
int no_of_components;
stack <int> mystack;
int main(){
cin >> n;
for (int i=0; i<n; i++){
int X;
cin >> X;
graph[X-1].push_back(i);
}
for (int i=0; i<n; i++){
if (components[i]>0) continue;
no_of_components++;
mystack.push(i);
components[i]=no_of_components;
while (mystack.empty()==false){
int v;
v=mystack.top();
mystack.pop();
for (int u=0; u<graph[v].size(); u++){
if (components[u]>0) continue;
mystack.push(u);
components[u]=no_of_components;
}
}
}
cout << no_of_components;
return 0;
}
【问题讨论】:
标签: c++ graph depth-first-search connected-components