關於用c建一個棧求下一個較大值
阿新 • • 發佈:2018-12-16
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int max_size = 100414; struct Node{ int x, id; }; class stack{ private: int size; Node sta[max_size]; public: stack(){size = 0;} void push(Node x); Node top(); void pop(); bool empty(); }; void stack::push(Node x){ sta[size++] = x; } Node stack::top(){ return sta[size-1]; } void stack::pop(){ size--; } bool stack::empty(){ return size == 0; } int rec[max_size]; int book[max_size]; int main(){ int T, n, i; Node t1, t2; scanf("%d", &T); while(T--){ stack s1; scanf("%d", &n); for(i = 1; i <= n; i++){ scanf("%d", &rec[i]); t1.x = rec[i], t1.id = i; while(!s1.empty()){ t2 = s1.top(); if(t2.x < t1.x){ s1.pop(); book[t2.id] = t1.x; } else break; } s1.push(t1); } while(!s1.empty()){ t2 = s1.top(); s1.pop(); book[t2.id] = -1; } for(i = 1; i <= n; i++){ printf("%d-->%d\n", rec[i], book[i]); } if(T) printf("\n"); } return 0; }