The users inputs the number of vertices ( n ) and then - in the next n lines - how the vertices are connected, namely that the number x in i -th line means that vertex i is connected with vertex x (the graph is undirected). The task is to find the number of connected components in this graph, and my code - for some reason I'm not able to find - outputs wrong values (for example, with input 4 2 1 2 4 , my code outputs 4 instead of 2 ). Any help greatly appreciated.
#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;
}
In your code there is a confusion between the counter u
which allows you to iterate through the connections of the node v, and the connections themselves:
v
is a node graph[v]
is the vector of connections u
is an index in in the vector of connections graph[v][u]
is the node connected to v
and component[graph[v][u]]
the component marker you have to update So you have to correct the inner for-loop as follows:
for (int u=0; u<graph[v].size(); u++){
if (components[graph[v][u]]>0) continue;
mystack.push(graph[v][u]);
components[graph[v][u]]=no_of_components;
}
Then works as expected.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.