题意:
已知两堆牌数均为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;
}