POJ3087 Shuffle'm Up【簡單模擬】
Shuffle'm Up
Time Limit: 1000MS | Memory Limit: 65536K |
Total Submissions: 15665 | Accepted: 7143 |
Description
A common pastime for poker players at a poker table is to shuffle stacks of chips. Shuffling chips is performed by starting with two stacks of poker chips, S1 and S2, each stack containing C
The actual shuffle operation is performed by interleaving a chip from S1 with a chip from S2 as shown below for C = 5:
The single resultant stack, S12, contains 2 * C chips. The bottommost chip of S12 is the bottommost chip from S2
After the shuffle operation, S12
For this problem, you will write a program to determine if a particular resultant stack S12 can be formed by shuffling two stacks some number of times.
Input
The first line of input contains a single integer N, (1 ≤ N ≤ 1000) which is the number of datasets that follow.
Each dataset consists of four lines of input. The first line of a dataset specifies an integer C, (1 ≤ C ≤ 100) which is the number of chips in each initial stack (S1 and S2). The second line of each dataset specifies the colors of each of the C chips in stack S1, starting with the bottommost chip. The third line of each dataset specifies the colors of each of the C chips in stack S2 starting with the bottommost chip. Colors are expressed as a single uppercase letter (Athrough H). There are no blanks or separators between the chip colors. The fourth line of each dataset contains 2 * C uppercase letters (A through H), representing the colors of the desired result of the shuffling of S1 and S2 zero or more times. The bottommost chip’s color is specified first.
Output
Output for each dataset consists of a single line that displays the dataset number (1 though N), a space, and an integer value which is the minimum number of shuffle operations required to get the desired resultant stack. If the desired result can not be reached using the input for the dataset, display the value negative 1 (−1) for the number of shuffle operations.
Sample Input
2
4
AHAH
HAHA
HHAAAAHH
3
CDE
CDE
EEDDCC
Sample Output
1 2
2 -1
Source
問題描述:給定s1,s2兩副撲克,順序從下到上。依次將s2,s1的撲克一張一張混合。例如s1=ABC; s2=DEF. 則第一次混合後為DAEBFC。 然後令前半段為s1, 後半段為s2。對於每個測試樣例,有兩個輸出x,y。x表示第幾組測試,y:如果可以變換成所給出的字串,輸出變換次數即可;否則,輸出-1。
解題思路:簡單模擬,關鍵是怎樣判斷不能變換成目標字串,可以使用集合set儲存已經變換得到的字串,如果再次出現說明繼續轉換也不能成功。
AC的C++程式:
#include<iostream>
#include<string>
#include<set>
using namespace std;
int main()
{
int T,len;
cin>>T;
for(int t=1;t<=T;t++){
string s1,s2,s,p;
set<string>S;//儲存已經出現過的字串
cin>>len>>s1>>s2>>s;
int count=0;
cout<<t<<" ";
for(;;){
//進行一次轉換
p=s1+s2;
for(int i=0;i<len;i++){
p[i*2+1]=s1[i];
p[i*2]=s2[i];
}
count++;//轉換的次數加一
if(p==s){//成功,輸出次數並退出
cout<<count<<endl;
break;
}
else if(S.count(p)){//失敗,而且p已經出現過了,繼續轉換也不能成功
cout<<"-1"<<endl;
break;
}
else{//失敗,但是轉換的字串還未出現過,就加入S中,並使更新s1和s2的值
S.insert(p);
s1=p.substr(0,len);
s2=p.substr(len,len);
}
}
}
return 0;
}