标签:i+1 out cout return nbsp space == lib while
这是一个栈的入门题,我用了STL,很懒,不想用数组模拟栈,开了4个栈,也是醉了。
In:表示进来的队列
Out:表示出站的队列
To:模拟进站与出站
还有一个用来掉头(进来的时候)
我来举一个小例子
比如出站序列为 5 4 1 2 3
In 栈底 5 4 3 2 1
Out 3 2 1 4 5
首先 to为空,out栈顶为5,不匹配,in.pop(),to 1,in 5 4 3 2
To.pop()和out.top()不匹配 继续 in:5 4 3 to:1 2
To.pop()和out.top()不匹配 继续 in:5 4 to:1 2 3
To.pop()和out.top()不匹配 继续 in:5 to:1 2 3 4
To.pop()和out.top()不匹配 继续 in: to:1 2 3 4 5
好了,To.pop()和out.top()匹配了,to.pop(),out.pop(); in: to:1 2 3 4 out:3 2 1 4
To.pop()和out.top()匹配 ,to.pop(),out.pop(); in: to:1 2 3 out:3 2 1
关键来了,现在to和out不匹配,但是in已经为空了,故结束
嗯,大体思路就是这样,我的第一篇blog~~~
标程:
#include<bits/stdc++.h>
using namespace std;
int n;
stack<int>in;
stack<int>to;
stack<int>out;
stack<int>cun;
int main()
{
cin>>n;
int x;
for(int i=1;i<=n;i++)
{
cin>>x;
cun.push(x);
in.push(n-i+1);
}
for(int i=1;i<=n;i++)
{
out.push(cun.top());
cun.pop();
}
to.push(in.top());
in.pop();
while(!in.empty()||!to.empty())
{
if(out.top()==to.top())
{
out.pop();
to.pop();
}
if(to.empty()&&!in.empty())
{
to.push(in.top());
in.pop();
}
if(to.empty()&&in.empty()&&!out.empty())
{
cout<<"NO"<<endl;
goto next;
}
if(to.empty()&&in.empty()&&out.empty())
{
cout<<"YES"<<endl;
goto next;
}
if(((out.top()!=to.top()))&&!in.empty())
{
to.push(in.top());
in.pop();
}
if(to.empty()&&in.empty()&&!out.empty())
{
cout<<"NO"<<endl;
goto next;
}
if(to.empty()&&in.empty()&&out.empty())
{
cout<<"YES"<<endl;
goto next;
}
if(out.top()!=to.top()&&in.empty())
{
cout<<"NO"<<endl;
goto next;
}
}
if(out.size()>0)
{
cout<<"NO"<<endl;
goto next;
}
cout<<"YES"<<endl;
next:
return 0;
}
标签:i+1 out cout return nbsp space == lib while
原文地址:http://www.cnblogs.com/war1111/p/7279388.html