This is what the code is for: https://www.codechef.com/LRNDSA04/problems/STACKS
Here is the code snippet:
#include<bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t; cin >> t;
while (t--)
{
int n; cin >> n;
vector<int> a;
while(n--) {
int x; cin >> x;
if(a.empty()) {
a.push_back(x);
} else {
vector<int>::iterator it = upper_bound(a.begin(), a.end(), x);
int pos = it - a.begin();
if(pos == a.size()) {
if(a[pos] > x) {
a[pos] = x;
} else {
a.push_back(x);
}
} else {
a[pos] = x;
}
}
}
cout << a.size();
for(auto e: a) {
cout << " " << e;
}
cout << "\n";
}
return 0;
}
Input to this program is:
2
6
3 4 5 1 1 2
8
14 5 13 19 17 10 18 12
The Unexpected output it generates:
3 1 1 2
3 5 10 12
If the input is changed to:
2
8
14 5 13 19 17 10 18 12
6
3 4 5 1 1 2
It shows up correct output:
4 5 10 12 18
3 1 1 2
The test case with 8 numbers as input if its position is altered in the input file. Then this behavior is observed.
When looking at the run of the code via gdb
, it gives expected output for both input files, no problem then.
The output is not justified, what am I missing to see?