My program gives an incorrect output for test cases other than 1. I figured out that I should change the values of every element in vec
and visited to 0. I can do it for visited but I get an error for vec
.
#include <bits/stdc++.h>
using namespace std;
vector <int> vec[100001];
int visited[100001];
void dfs(int node)
{
visited[node] = 1;
for (int child : vec[node])
{
if (!visited[child])
dfs(child);
}
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--)
{
int n, e, a, b;
cin >> n;
cin >> e;
for (int i = 0; i < e; ++i)
{
cin >> a >> b;
vec[a].push_back(b);
vec[b].push_back(a);
}
long long c = 0;
for (int i = 0; i < n; ++i)
{
if (!visited[i])
{
dfs(i);
++c;
}
}
cout << c << '\n';
memset(visited, 0, sizeof(visited));
fill(vec.begin(), vec.end(), 0);
}
}
I used memset()
for visited and fill()
for vec. How to resolve this issue?
Input:
2
4
2
0 1
0 2
8
0
Expected output:
2
8
Output:
CC.cpp: In function 'int main()':
CC.cpp:47:18: error: request for member 'begin' in 'vec', which is of non-class type 'std::vector<int> [100001]'
fill(vec.begin(), vec.end(), 0);
^
CC.cpp:47:31: error: request for member 'end' in 'vec', which is of non-class type 'std::vector<int> [100001]'
fill(vec.begin(), vec.end(), 0);
If I remove the line with fill()
:
Output:
2
6
The program is for finding the number of connected components in a graph.