标签:思想 body mission 位置 ++ city nes break table
| Time Limit: 1000MS | Memory Limit: 10000K | |
| Total Submissions: 24762 | Accepted: 9715 |
Description

Input
Output
Sample Input
5 1 2 3 4 5 5 4 1 2 3 0 6 6 5 4 3 2 1 0 0
Sample Output
Yes No Yes
Source
复杂度O(n^2),不论什么元素x出栈前。全部大于x的元素必须出栈,栈内的元素值必须小于x,由于大于x的元素后于x入栈,小于x的值先于x入栈;
#include <cstdio>
using namespace std;
const int maxn=1000+5;
int a[maxn],b[maxn];//a数组储存入栈的序列。b数组存储要推断的序列
int main()
{
int n,i,j,k;
while(scanf("%d",&n)&&n)
{
while(scanf("%d",&b[0])&&b[0])
{
for(i=1;i<n;i++)
scanf("%d",&b[i]);
for(i=1,j=0,k=0;i<=n&&j<n;i++,j++)
{
a[j]=i;
while(a[j]==b[k])//进行推断(出栈的顺序是否合理)
{
if(j>0) j--;//推断下一个
else
{
a[j]=0;
j--;
}
k++;
if(j==-1) break;
}
}
if(k==n) printf("Yes\n");//假设所有匹配就输出yes
else printf("No\n");
}
printf("\n");
}
return 0;
}用STL栈来实现。思想上是一样的:代码略有不同#include <cstdio>
#include <stack>
using namespace std;
const int maxn=1000+5;
int a[maxn];
int main()
{
int n,i,k;
while(scanf("%d",&n)&&n)
{
stack<int>s;//设立一个栈储存按顺序进栈的序列 (一个空栈)
while(scanf("%d",&a[0])&&a[0])
{
for(i=1;i<n;i++)
scanf("%d",&a[i]);//要进行推断出栈的序列
for(i=1,k=0;i<=n;i++)
{
s.push(i);//进栈
while(s.top()==a[k])//推断栈顶元素和a数组是否相等
{
if(!s.empty()) s.pop();//栈不为空就出栈
k++;//推断下一个位置
if(s.empty()) break;//直到栈空就结束循环
}
}
if(k==n) printf("Yes\n");//全然匹配就输出yes
else printf("No\n");
}
printf("\n");
}
return 0;
}
栈的基本思想的实现。水题,主要要掌握这样的思想。
标签:思想 body mission 位置 ++ city nes break table
原文地址:http://www.cnblogs.com/ljbguanli/p/7116150.html