poj 3087 Shuffle'm Up 模拟(map记录)

题意:已知两堆牌数均为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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值