this problem is a very classic problem which can use stack to solve. the problem can be searched through many source site.
#include<cstdio> #include<stack>//表明要调用关于栈的文件吧; using namespace std; const int maxn=1000+10; 使用栈 int n,target[maxn]; int main() { while(scanf("%d",&n)==1) { stack<int> s;//生成一个元素为int的栈吧; int A=1,B=1; for(int i=1;i<=n;i++) scanf("%d",&target[i]);//读入出栈顺序; int ok =1; while(B<=n) { if(A==target[B]){A++;B++;}//进等于出就直接出; else if(!s.empty()&&s.top()==target[B]) {s.pop();B++;}//如果S不为空栈并且s的栈顶元素正好为需要的B元素就直接把顶端元素放出去; else if(A<=n)s.push(A++);//还有合法的未进栈元素就让其进栈; else {ok=0;break;} } printf("%s ",ok?"Yes":"No"); } return 0; }