您的位置:首页 > 其它

POJ 1363 解题报告

2015-03-24 07:16 381 查看
这道题不难但是题目很难理解。看了测试样例才明白,如果入栈顺序是递增的:1,2,3,4,5. 那么给出一个出栈顺序,比如5,4,1,2,3,判断这个出栈顺序是否可能。

我这里就是按照题意模拟的。比如碰到5,就将小于等于5的都入栈(1,2,3,4,5),然是将5出栈(判断这时栈顶一定是5),同样地,之后遇到4,已经没有什么可入栈了,栈顶是4,出栈,再遇到1,同样没什么可入栈的,栈顶元素是3,不是1,说明不可能。

thestoryofsnow1363Accepted156K110MSC++1354B
/*
ID: thestor1
LANG: C++
TASK: poj1363
*/
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <limits>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <cassert>

using namespace std;

int main()
{
int N;
scanf("%d", &N);
while (N)
{
int num;
scanf("%d", &num);
// the number of numbers input
int cnt = 1;
// fprintf(stderr, "num: %d, cnt: %d\n", num, cnt);

if (!num)
{
printf("\n");
scanf("%d", &N);
continue;
}

int instacktop = 1;
stack<int> outstack;

bool flag = true;
while (true)
{
while (instacktop <= N && instacktop <= num)
{
outstack.push(instacktop);
instacktop++;
}

if (outstack.empty() || outstack.top() != num)
{
flag = false;
break;
}
outstack.pop();

if (cnt == N)
{
break;
}

scanf("%d", &num);
cnt++;
// fprintf(stderr, "num: %d, cnt: %d\n", num, cnt);
}

// get the rest of numbers
while (cnt < N)
{
scanf("%d", &num);
cnt++;
// fprintf(stderr, "num: %d, cnt: %d\n", num, cnt);
}

if (flag)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: