[sjtu oj]4370 Min Stack
使用两个栈进行维护
st中存储初始栈内容,并记录节点编号
minn栈中记录各个编号对应的最小值(通过继承上一个与当前值比较实现)
如何实现操作为O(1):在push&pop的同时维护minn栈
代码如下
#include<iostream> #include<cstring> #define ll long long using namespace std; const ll MAXN=1e6+5; ll minn[MAXN]; class Stack { private: struct Node { ll data;ll num; Node* nex; Node(const ll s,Node *nexx=NULL):data(s),nex(nexx){} Node():nex(NULL){} }; Node* Top; int cnt=0; public: Stack(){Top=new Node;}; void pop(); ll top()const; void push(ll s); ll getmin(); ~Stack(); }; Stack a,b; void Stack::pop() { if(Top->nex==NULL) { puts("Empty"); return ; } cnt--; Node* p=Top->nex; Top->nex=p->nex; delete p; } ll Stack::top()const { if(Top->nex==NULL) { puts("Empty"); return -1; } return Top->nex->data; } void Stack::push(ll s) { Node *p=new Node; p->data=s; p->num=++cnt; if(Top->nex!=NULL) minn[cnt]=min(minn[Top->nex->num],s); else minn[cnt]=s; p->nex=Top->nex; Top->nex=p; } ll Stack::getmin() { if(Top->nex==NULL) { puts("Empty"); return -1; } return minn[Top->nex->num]; } Stack::~Stack() { Node *p=Top; while(p) { Node *q=p->nex; delete p; p=q; } } void read(ll &p) { char s=getchar();p=0; while(!isdigit(s)) s=getchar(); for(;isdigit(s);s=getchar()) p=p*10+s-'0'; } void print(ll p) { if(p/10) print(p/10); putchar(p%10+'0'); } int main() { //memset(minn,0x3f,sizeof(minn)); ll n,k; ll s; Stack st; read(n); for(ll i=1;i<=n;i++) { read(k);++k; ll tem; switch(k) { case 1:read(s); st.push(s); break; case 2:st.pop(); break; case 3:tem=st.top();if(tem!=-1) {print(tem);puts("");} break; case 4:tem=st.getmin(); if(tem!=-1) {print(tem);puts("");} break; } } return 0; }