Dana jest tablica. Kolejną Większą Liczbą liczby x jest najbliższa (przeglądając kolejne elementy w prawą stronę) większa od niej liczba występująca w tablicy. Jeśli KWL dla x nie istnieje, wypisz -1 dla tego numeru. Należy założyć, że tablica jest “cykliczna”, tzn po osiągnięciu ostatniego elementu wyszukiwanie kontynuowane jest od indeksu 0.
Wejście: [1, 2, 1, 4, 1]
Wyjście: [2, 4, 4, -1, 2]
Zgodnie z: https://stackoverflow.com/questions/19720349/find-next-higher-element-in-an-array-for-each-element
udało mi sie napisać taki kod:
#include <iostream>
#include <stack>
#include <vector>
int get(std::stack<int> &s){
int x = s.top();
s.pop();
return x;
}
int main(){
std::stack<int> s;
std::vector<int> data{1,2,1,4,1};
s.push(data.at(0));
data.erase(data.begin());
for(int x : data){
if(!s.empty()){
while(true){
if(s.empty() || s.top() > x){
break;
}
std::cout << get(s) << " : " << x << std::endl;
}
}
s.push(x);
}
while(!s.empty()){
std::cout << get(s) << " : -1\n";
}
return 0;
}
Jednak daje złą odpowiedź oraz jest jakoś porozwalane
Prosze o pomoc