Train Problem I
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 26603 Accepted Submission(s):
10061
Problem Description
As the new term comes, the Ignatius Train Station is
very busy nowadays. A lot of student want to get back to school by train(because
the trains in the Ignatius Train Station is the fastest all over the world ^v^).
But here comes a problem, there is only one railway where all the trains stop.
So all the trains come in from one side and get out from the other side. For
this problem, if train A gets into the railway first, and then train B gets into
the railway before train A leaves, train A can't leave until train B leaves. The
pictures below figure out the problem. Now the problem for you is, there are at
most 9 trains in the station, all the trains has an ID(numbered from 1 to n),
the trains get into the railway in an order O1, your task is to determine
whether the trains can get out in an order O2.






Input
The input contains several test cases. Each test case
consists of an integer, the number of trains, and two strings, the order of the
trains come in:O1, and the order of the trains leave:O2. The input is terminated
by the end of file. More details in the Sample Input.
Output
The output contains a string "No." if you can't
exchange O2 to O1, or you should output a line contains "Yes.", and then output
your way in exchanging the order(you should output "in" for a train getting into
the railway, and "out" for a train getting out of the railway). Print a line
contains "FINISH" after each test case. More details in the Sample
Output.
Sample Input
3 123 321
3 123 312
Sample Output
Yes.
in
in
in
out
out
out
FINISH
No.
FINISH
Hint
HintAuthor
Ignatius.L
Recommend
巧妙利用栈解题,列车进站的问题。可以进站马上出站,出站的顺序可以随意定。
题意:有N辆火车,以序列1方式进站,判断是否能以序列2方式出栈。进站不一定是一次性进入,也就是说中途可以出站。
附上代码:
1 #include <iostream> 2 #include <cstdio> 3 #include <stack> 4 using namespace std; 5 int main() 6 { 7 int n,i,j,m,num; 8 char str1[105],str2[105]; 9 int flag[105]; 10 while(~scanf("%d %s %s",&n,str1,str2)) 11 { 12 stack <char> s; //定义一个栈 13 while(!s.empty()) //如果栈不为空,则必须将栈清空 14 s.pop(); 15 i=j=num=0; 16 while(j<n) 17 { 18 if(s.empty()||s.top()!=str2[j]&&i<n) //如果栈是空的,或者当前要出来的车不是栈中的第一辆可出来的车,则存入当前这辆车 19 { 20 s.push(str1[i]); 21 flag[num++]=1; //并标记为1,表示进站 22 i++; 23 } 24 else 25 { 26 if(s.top()==str2[j]) //如果此时栈中可以出站的车正好是要求出站的车,则马上从栈中出来 27 { 28 s.pop(); 29 flag[num++]=0; //出站车,标记为0 30 j++; 31 } 32 33 else //如果i>n,则跳出循环 34 break; 35 } 36 } 37 if(s.empty()) //如果此时栈是空的,则表示序列1的列车以序列2的顺序全部出去,因次输出Yes.,否则输出No. 38 { 39 printf("Yes. "); 40 for(i=0; i<num; i++) 41 { 42 if(flag[i]) //标记为1就进来一辆车,0则出去一辆车 43 printf("in "); 44 else 45 printf("out "); 46 } 47 } 48 else 49 printf("No. "); 50 printf("FINISH "); 51 } 52 return 0; 53 }