POJ 1363:http://poj.org/problem?id=1363
判断一个出栈序列是否合法
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAX = 1005;
int main(int argc, char const *argv[])
{
int n,cntout,cntin,top,cnt;
int stack[MAX];
int in[MAX],out[MAX];
while (scanf("%d",&n), n) {
while (scanf("%d",&out[0]), out[0]) {
int flag = 1;
memset(stack,0,sizeof(stack));
top = cntout = cntin = cnt = 0;
in[0] = 1;
for (int i = 1; i < n; i ++) {
scanf("%d",&out[i]);
in[i] = i + 1;
}
stack[top ++] = in[cntin ++];
while (top > 0) {
while (out[cntout] != stack[top - 1] && cntin < n) {
stack[top ++] = in[cntin ++];
}
if (cntin == n && stack[top - 1] != out[cntout]) {
flag = 0;
break;
}
top --;
cntout ++;
if (top == 0 && cntin < n) {
stack[top ++] = in[cntin ++];
}
}
if (flag) {
printf("Yes\n");
} else {
printf("No\n");
}
}
printf("\n");
}
return 0;
}
POJ 3250:http://poj.org/problem?id=3250
单调栈
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
using namespace std;
int main()
{
int n;
while (~scanf("%d",&n)) {
long long ans = 0;
stack<int> s;
int h;
for (int i = 1; i <= n; i ++) {
scanf("%d",&h);
while (!s.empty() && s.top() <= h) {
s.pop();
}
ans += s.size();
s.push(h);
}
printf("%lld\n",ans);
}
return 0;
}