Garmaine Staff asked 2 years ago

right now I'm trying to solve a competitive programming problem but whenever I try to push to a vector (bb), it gives me a segfault. I've tried fixing this by switching from stack to vector and by just attempting to push a regular integer with no variables, but I've had no luck.

#include <bits/stdc++.h>
#include <iostream>
#include <stack>
using namespace std;


int main(){
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    int t, n;
    cin >> t;

    for(int e = 0; e < t; e++){

        cin >> n;
        int want = 1, temp;
        bool flag = true;
        stack<int> mountain;
        vector<int> bb;

        for(int i = 0; i < n; i++){
            cin >> temp;
            mountain.push(temp);
        }

        while(!mountain.empty() || !bb.empty()){

            if(mountain.top() == want){
                mountain.pop();
                want++;

            }else if(!bb.empty() && bb.back() == want){
                bb.pop_back();
                want++;

            }else if(mountain.size() > 1){
                 bb.push_back(mountain.top()); // <-----------------
                mountain.pop();

            }else{
                cout << "N\n";
                flag = false;
                break;

            }
            if(flag && want == n + 1) cout << "Y\n";
        } 

    }   

    return 0;
    }

If you need any context for the problem it can be found here.