題目傳送門:
http://acm.hdu.edu.cn/showproblem.php?pid=1022
題目大意是給出一個入棧的序列,判斷一個給出的序列是否可能是一個合法的出棧序列,若是,給出入棧和出棧的過程。
#include <iostream>
#include <cstring>
using namespace std;
int main(int argc, char const *argv[])
{
int n,cntout,cntin,top,cnt; //标記目前資訊
int rec[]; //記錄入棧出棧過程
char stack[]; //棧
char in[],out[]; //入棧出棧順序
while (cin >> n) {
int flag = ; // 首先假定出棧順序合法
memset(stack,,sizeof(stack));
top = cntout = cntin = cnt = ;
cin >> in >> out;
stack[top ++] = in[cntin ++];// 首元素入棧
rec[cnt ++] = ;
while (top > ) {
// 當棧頂元素不是下一個要出棧元素且還有元素未入棧時入棧
while (out[cntout] != stack[top - ] && cntin < n) {
stack[top ++] = in[cntin ++];
rec[cnt ++] = ;
}
/*當 全部元素都已入棧,棧頂元素仍不是下一個要出棧的元素,出棧順序非法 */
if (cntin == n && stack[top - ] != out[cntout]) {
cout << "No." << endl << "FINISH" << endl;
flag = ;
break;
}
// 棧頂元素已經是下一個要出棧的元素,棧頂元素出棧
top --;
cntout ++;
rec[cnt ++] = ;
// 棧空但仍有元素未入棧,隊首元素入棧
if (top == && cntin < n) {
stack[top ++] = in[cntin ++];
rec[cnt ++] = ;
}
}
if (flag) {
cout << "Yes." << endl;
for (int i = ; i < cnt; ++i)
{
if (rec[i]) {
cout << "in" << endl;
} else {
cout << "out" << endl;
}
}
cout << "FINISH" << endl;
}
}
return ;
}