3 123 321 3 123 312
Yes. in in in out out out FINISH No. FINISHFor the first Sample Input, we let train 1 get in, then train 2 and train 3. So now train 3 is at the top of the railway, so train 3 can leave first, then train 2 and train 1. In the second Sample input, we should let train 3 leave first, so we have to let train 1 get in, then train 2 and train 3. Now we can let train 3 leave. But after that we can't let train 1 leave before train 2, because train 2 is at the top of the railway at the moment. So we output "No.".HintHint
栈其实也就是一个容器而已~放一个又一个~当又要放的那个和栈最上面的那个相对应的时候,栈最上面的那个就跳出~直到栈空为止~~~
<span style="font-size:18px;">#include<stdio.h> #include<string.h> #include<stack> using namespace std; int main() { int k,i,n,j; char a[10],b[10],v[10]; while(~scanf("%d%s%s",&n,a,b)) { i=k=j=0; stack<char>s; while(!s.empty()) s.pop(); while(i<n) { s.push(a[i++]); v[k++]=1; while(!s.empty()&&s.top()==b[j]) { s.pop(); j++; v[k++]=0; } } if(!s.empty()) printf("No.\n"); else { printf("Yes.\n"); for(i=0;i<k;i++) { if(v[i]) printf("in\n"); else printf("out\n"); } } printf("FINISH\n"); } return 0; }</span>
还有南阳OJ的括号配对问题也用到了栈~~~
括号配对问题
时间限制:3000 ms | 内存限制:65535 KB
难度:3
描述
现在,有一行括号序列,请你检查这行括号是否配对。
输入
第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符
输出
每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No
样例输入
3
[(])
(])
([[]()])
样例输出
No
No
Yes
代码如下~
<span style="font-size:18px;">#include<stdio.h> #include<string.h> #include<iostream> #include<stack> using namespace std; char a[11000]; int main() { int n; int i,j; int len; scanf("%d",&n); getchar(); while(n--) { gets(a); len=strlen(a); if(len%2==1) printf("No\n"); else { if(a[0]==']'||a[0]==')') printf("No\n"); else { stack<char>s;//栈定义初始化 s.push(a[0]); for(i=1;i<len;i++) { if(s.size()==0) s.push(a[i]); //要先判断栈里面有没有数据,要不然s.top()会出现错误 else { if(s.top()=='['&&a[i]==']') s.pop(); else if(s.top()=='('&&a[i]==')') s.pop(); else s.push(a[i]); } } if(s.empty()) printf("Yes\n"); else printf("No\n"); } } } return 0; }</span>
针对这道题还有一种简便方法~虽然不用栈~但和栈的思想差不多~~便于理解~~
<span style="font-size:18px;">#include<stdio.h> #include<string.h> using namespace std; char stack[11000],c[11000]; int main() { int n,top,i; scanf("%d",&n); getchar(); while(n--) { top=1; memset(stack,0,sizeof(stack)); gets(stack); c[0]=stack[0]; if(strlen(stack)%2==1) printf("No\n"); else if(stack[0]==']'||stack[0]==')') printf("No\n"); else { for(i=1;i<strlen(stack);i++) { c[top]=stack[i]; if(c[top-1]=='['&&c[top]==']') top--; else if(c[top-1]=='('&&c[top]==')') top--; else top++; } if(top==0) printf("Yes\n"); else printf("No\n"); } } return 0; }</span>