-2

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.

Nishchay
  • 41
  • 6
  • 4
    Start by getting rid of `#include ` and `using namespace std;`. [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/q/1452721) [Why should I not `#include `](https://$SITEURL$/q/31816095) – L. F. Apr 06 '20 at 05:32
  • Thanks. How to fix the error though? – Nishchay Apr 06 '20 at 05:39
  • Show the content of the error message first. – L. F. Apr 06 '20 at 05:40
  • What is the progrtam supposed to do? Show the expected output for a given input vs the actual output. – Jabberwocky Apr 06 '20 at 05:47

1 Answers1

1

fill(vec.begin(), vec.end(), 0);

This line is the problem. vec is an array of vectors. It is an array. It has no begin() and end() like a vector does.

You have an array of 100001 vectors you want to clear. Just iterate over your array of vectors and clear() each vector.

Note that filling with zeroes is not the same as clearing. But I'm quite sure you want to clear the vectors

sparik
  • 1,181
  • 9
  • 16