PTA5-19 列车厢调度 (25分)【stack】

    xiaoxiao2021-03-25  167

    5-19 列车厢调度   (25分)

    1 ====== <--移动方向 / 3 ===== \ 2 ====== -->移动方向

    大家或许在某些数据结构教材上见到过“列车厢调度问题”(当然没见过也不要紧)。今天,我们就来实际操作一下列车厢的调度。对照上方的ASCII字符图,问题描述如下:

    有三条平行的列车轨道(1、2、3)以及1-3和2-3两段连接轨道。现有一列车厢停在1号轨道上,请利用两条连接轨道以及3号轨道,将车厢按照要求的顺序转移到2号轨道。规则是:

    每次转移1节车厢;处在1号轨道的车厢要么经过1-3连接道进入3号轨道(该操作记为"1->3"),要么经过两条连接轨道直接进入2号轨道(该操作记为"1->2");一旦车厢进入2号轨道,就不可以再移出该轨道;处在3号轨道的车厢,只能经过2-3连接道进入2号轨道(该操作记为"3->2");显然,任何车厢不能穿过、跨越或绕过其它车厢进行移动。

    对于给定的1号停车顺序,如果经过调度能够实现2号轨道要求的顺序,则给出操作序列;如果不能,就反问用户 Are(你) you(是) kidding(凯丁) me(么)?

    输入格式:

    两行由大写字母组成的非空字符串,第一行表示停在1号轨道上的车厢从左到右的顺序,第二行表示要求车厢停到2号轨道的进道顺序(输入样例1中第二行CBA表示车厢在2号轨道的停放从左到右是ABC,因为C最先进入,所以在最右边)。两行字符串长度相同且不超过26(因为只有26个大写字母),每个字母表示一节车厢。题目保证同一行内的字母不重复且两行的字母集相同。

    输出格式:

    如果能够成功调度,给出最短的操作序列,每个操作占一行。所谓“最短”,即如果1->2可以完成的调度,就不要通过1->3和3->2来实现。如果不能调度,输出 "Are you kidding me?"

    输入样例1:

    ABC CBA

    输出样例1:

    1->3 1->3 1->2 3->2 3->2

    输入样例2:

    ABC CAB

    输出样例2:

    Are you kidding me?

    #include<iostream> #include<cstdio> #include<math.h> #include<cstring> #include<climits> #include<string> #include<queue> #include<iostream> #include<cstdio> #include<cmath> #include<cstring> #include<climits> #include<string> #include<queue> #include<stack> #include<set> #include<map> #include<list> #include<sstream> #include<algorithm> #include<vector> using namespace std; #define rep(i,j,k)for(i=j;i<k;i++) #define per(i,j,k)for(i=j;i>k;i--) #define MS(x,y)memset(x,y,sizeof(x)) #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define ll long long const int INF=0x7ffffff; const int M=1e4+10; int i,j,k,n,m,len; stack<char>s1; stack<char>s2; stack<char>s3; vector<int>step[M]; int main() { char s[M],ss[M]; while(cin>>s){ getchar(); cin>>ss; for(i=strlen(s)-1;i>=0;i--)s1.push(s[i]); for(i=strlen(ss)-1;i>=0;i--)s2.push(ss[i]); //for(i=0;i<M;i++)step[i].clear(); k=0;int flag=0; while(1){ if(!s1.empty()&&s1.top()==s2.top()){ step[k].push_back(1); step[k].push_back(2); k++; s1.pop();s2.pop(); } else if(!s3.empty()&&s2.top()==s3.top()){ step[k].push_back(3); step[k].push_back(2); k++; s3.pop();s2.pop(); } else { if(!s1.empty()){ char a=s1.top();s1.pop(); s3.push(a); step[k].push_back(1); step[k].push_back(3); k++; } } if(s2.empty()){ flag=1;break; } if(s1.empty()&&s3.top()!=s2.top()){ flag=0; break; } } if(!flag)cout<<"Are you kidding me?"<<endl; else { for(i=0;i<k;i++) cout<<step[i][0]<<"->"<<step[i][1]<<endl; } } return 0; }

    转载请注明原文地址: https://ju.6miu.com/read-5154.html

    最新回复(0)