spookymath
spookymath

Reputation: 1

Unable to access elements in a 2-D Vector

I am trying to solve the following problem using C++ and I am facing an unusual error (in the sense that I am unable to access the elements in a 2-D Vector using indices whose values are stored in variables.)

#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <utility>
#include <algorithm>

using namespace std;

int main()
{
    int tc; cin >> tc;
    while(tc--)
    {
        int n; cin >> n;
        
        vector<int> f(n+1, 0);
        for(int i=0; i<n; i++) cin >> f[i+1];
        f[0] = -1;

        vector<int> p(n+1, 0);
        for(int i=0; i<n; i++) cin >> p[i+1];
        p[0] = -1;

        vector<vector<int>> graph(n+1, vector<int>());
        map<int, vector<int>> levels;

        for(int i=1; i<n+1; i++) graph[p[i]].push_back(i);

        queue<pair<int, int>> Q;
        for(int i=0; i<graph[0].size(); i++) Q.push({graph[0][i], 0});

        while(!Q.empty())
        {
            int p = Q.front().first;
            int lv = Q.front().second;

            levels[lv].push_back(p);

            for(int i=0; i<graph[p].size(); i++) Q.push({graph[p][i], lv+1});
            Q.pop();
        }

        int x = levels.size() - 2;
        int ans = 0;

        while(x >= 0)
        {
            for(int k=0; k<levels[x].size(); k++)
            {
                int root = levels[x][k];
                // cout << root << '-'; // works
                // cout << graph[root].size() << ' '; // works
                // cout << graph[root][0] << ' '; // doesnt work

                // for(int i=1; i<graph[root].size(); i++)
                // {
                //     mn = min(mn, f[graph[root][i]]);
                //     tmp += f[graph[root][i]];
                // }

                // tmp -= mn;
                // ans += tmp;

                // if(f[root] < mn) f[root] = mn;
            }
            x -= 1;
            cout << endl;
        }

        // for(int i=0; i<levels[0].size(); i++)
        //     ans += levels[0][i];

        // cout << ans << '\n';
    }
}

I am specifically getting error at lines 54, 55 and 56. (which I have commented out above).

cout << root << '-'; // works
cout << graph[root].size() << ' '; // works
cout << graph[root][0] << ' '; // doesnt work

The first 2 statements seem to work. However the 3rd statement doesn't seem to give me any output when I try accessing an element. I have also tried to use cout << graph[3][0] in place of cout << graph[root][0] when root takes the value of 3. And the former seems to work.

I wanted to know what could be the reason for graph[root][0] to not show any output, although when I use constants such as graph[3][0], it seems to work.

Logic aside, what could be the syntax error in my code ?

Upvotes: 0

Views: 68

Answers (0)

Related Questions