题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1022
题目大意:
给你2个字符串,第一个字符串str1代表火车的入站顺序,第二个字符串str2代表出站序列,如果str1能满足str2的要求,就输出YES。并输入进站出站的顺序。
解题思路:
很裸的栈的应用。只要平时好好想过,就可以写出来。因为C++提供了stack可以用,非常方便的。。。
但是这个题还有一点需要思路,不是全部入站后才能出站,而是进站后,只要是离出站口最近,就可以出站(可以连着多个出站后再入站)。这就需要自己思考到底怎么做了。
我的思路是:
火车进站后则入栈,与出站顺序相比较,如果栈顶元素等于当前出站顺元素,则退栈,出站数+1。这样循环,直到栈顶元素不等于出站元素为止,继续火车进站即可。
如果全部进站并处理后,栈为空,则说明出站顺序可以满足。
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<vector>
#include<stack>
#include<algorithm>
using namespace std;
int main()
{
int num, total;
string str1, str2;
vector<string> v;
stack<int> s;
while(scanf("%d", &num) != EOF)
{
total = 0; //初始化
v.clear();
while(!s.empty())
s.pop();
cin>>str1>>str2;
for(int i = 0; i < num; ++i)
{
s.push(str1[i]);
v.push_back("in");
while(!s.empty() && s.top() == str2[total]) //total为巧妙之处
{
total++;
s.pop();
v.push_back("out");
}
}
if(s.empty())
{
printf("Yes.\n");
for(int i = 0; i < v.size(); ++i) //进站出站顺序
cout<<v[i]<<endl;
printf("FINISH\n");
}
else
printf("No.\nFINISH\n");
}
return 0;
}
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
#define MAXN 101
struct stack
{
int top;
char stackarr[MAXN];
};
stack s; //这个就是栈,不能在下面参数中传入s,那就是多个栈了。。。
void init() { s.top = -1; } //初始化
bool empty() { return s.top == -1 ? true : false; } //判断栈空
void push(char x) {s.stackarr[s.top++] = x; }//入栈
void pop() { s.top--; } //出栈
char gettop() { return s.stackarr[s.top]; }//栈顶元素
int main()
{
int num;
string str1, str2;
while(scanf("%d", &num) != EOF)
{
int k, count;
string out[2 * MAXN];
init();
k = count = 0;
cin>>str1>>str2;
for(int i = 0 ; i < num; ++i)
{
out[count++] = "in";
push(str1[i]);
while(!empty() && gettop() == str2[k])
{
pop();
k++;
out[count++] = "out";
}
}
if(empty())
{
printf("Yes.\n");
for(int i = 0; i < count; ++i)
cout<<out[i]<<endl;
printf("FINISH\n");
}
else
printf("No.\nFINISH\n");
}
return 0;
}