火车进栈出栈问题,根据刘汝佳大神的思路所写出来的代码,
用计算机来模拟火车进栈出栈即得出了结果
#include<stdio.h>
#include<string.h>
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
char o1[15],o2[15],outof[30];
int target[15],start[15],stack[15],top=0,count=0;
scanf("%s%s",o1,o2);
int i;
for(i=0;i<n;i++)
start[i]=o1[i]-'0';
for(i=0;i<n;i++)
target[i]=o2[i]-'0';
int ok=1,A=0,B=0;
while(B<n)
{
if(start[A]==target[B]) //模拟进一个出一个的状态
{
A++;
B++;
outof[count++]='i';
outof[count++]='o';
}
else if(top&&stack[top]==target[B]) //模拟从栈顶出来的列车
{
top--;
B++;
outof[count++]='o';
}
else if(A<n) //模拟进栈的列车
{
stack[++top]=start[A++];
outof[count++]='i';
}
else
{
ok=0;
break;
}
}
printf("%s\n",ok?"Yes.":"No.");
if(ok)
for(i=0;i<count;i++)
{
if(outof[i]=='i')
printf("in\n");
else if(outof[i]=='o')
printf("out\n");
}
printf("FINISH\n");
}
return 0;
}
还有一种方式可以做,那就是直接用vector容器来装,这个代码更简洁
t=2*n;
i=0;j=0;k=0;d=0;
while(t--)
{
if(d==o2[i])
{
v.pop_back();
f[j++]=1;
i++;
d=v.back();
}
else
{
v.push_back(o1[k++]);
f[j++]=0;
d=v.back();
}
}