題意:
已知兩堆牌數均為n的紙牌堆a和b的初始狀态, 按給定規則能将他們互相交叉組合成一堆牌str,再将str的最底下的n張牌歸為a,最頂的n張牌歸為b,依此循環下去。現在輸入a和b的初始狀态 以及 預想的最終狀态c,問a, b經過多少次洗牌之後,最終能達到狀态c,若永遠不可能相同,則輸出”-1”。
思路:
用map記錄一下目前str出現的狀态,如果目前的str在前面出現過(出現循環),那就輸出-1,因為無論再怎麼變換都不會出現終态c。若果沒有出現的話就繼續洗牌然後分牌,一直到找出為止。
附帶一個,string.append() 的用法:https://blog.csdn.net/wxn704414736/article/details/78551886
char數組的寫法
#include<iostream>
#include<string>
#include<cmath>
#include<ctype.h>
#include<memory.h>
#include<string.h>
#include<algorithm>
#include<map>
#include<iomanip>
#include<set>
#include<list>
#include<vector>
#include<stack>
#include<queue>
#define ll long long int
using namespace std;
const int maxn = 300;
int main()
{
int T; cin >> T;
for (int ii = 1; ii <= T; ii++)
{
char a[maxn], b[maxn], c[maxn * 2];
char str[maxn * 2];
map<string, int> Map; //Map.clear();
int n; cin >> n;
int cnt = 0;
cin >> a >> b >> c;
Map[c] = 1;
while (true)
{
int t = 0;
for (int i = 0; i < n; i++)
{
str[t++] = b[i];
str[t++] = a[i];
}
str[t] = '\0';//千萬不可以丢掉!!!
cnt++;
if (!strcmp(str, c))
{
cout << ii << " " << cnt << endl;
break;
}
if (Map[str] == 1)
{
cout << ii << " " << -1 << endl;
break;
}
Map[str] = 1;
for (int i = 0; i < n; i++)
a[i] = str[i];
for (int i = 0; i < n; i++)
b[i] = str[i + n];
a[n] = '\0';//千萬不可以丢掉!!!
b[n] = '\0';//千萬不可以丢掉!!!
}
}
return 0;
}
string的寫法
#include<iostream>
#include<string>
#include<cmath>
#include<ctype.h>
#include<memory.h>
#include<string.h>
#include<algorithm>
#include<map>
#include<iomanip>
#include<set>
#include<list>
#include<vector>
#include<stack>
#include<queue>
#define ll long long int
using namespace std;
const int maxn = 300;
int main()
{
int T; cin >> T;
for (int ii = 1; ii <= T; ii++)
{
string a, b, c;
//string str;//寫在這裡就錯了! 忘記改地方了,被坑了好久!
map<string, int> Map;
int n; cin >> n;
int cnt = 0;
cin >> a >> b >> c;
Map[c] = 1;
while (true)
{
string str;
int t = 0;
for (int i = 0; i < n; i++)
{
str += b[i];
str += a[i];
}
cnt++;
if (str == c)
{
cout << ii << " " << cnt << endl;
break;
}
if (Map[str] == 1)//如果出現過
{
cout << ii << " " << -1 << endl;
break;
}
Map[str] = 1;
a = str.substr(0, n);//a取上半部分
b = str.substr(n, n);//b取下半部分
}
}
return 0;
}