POJ 3087 *** Shuffle'm Up

本文介绍了一种通过交替叠加两张卡片堆并重新分配上下部分来实现特定目标堆的算法。利用搜索策略与哈希映射记录每一步状态,确保变换过程的有效性和正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:给定s1、s2两堆卡片,s1最底下一张放在s2最底下那张的上面,然后依次交错形成s堆。将s堆的上一半分给s2,下一半分给s1。

输入s1、s2、s,问s1、s2能否通过上述变换最终形成s。


想法:搜索,每对s1、s2做一次变换之后便查看结果是否等于s,用map做记录就可以了。


代码如下:


#pragma warning(disable:4996)
#include<iostream>
#include<cstdio>
#include<cmath>
#include<stack>
#include<queue>
#include<cstring>
#include<sstream>
#include<set>
#include<string>
#include<iterator>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
typedef long long ll;

char s1[105], s2[105], s[210], snow[210];

int main(void) {
	int n, length, cnt = 0;
	cin >> n;
	while (n--) {
		cin >> length;
		int ans = 0;

		cin >> s1 >> s2 >> s;
		map<string, int> path;
		path[s] = 1;
		while (1) {
			for (int i = 0; i < length; i++)
				snow[2 * i] = s2[i], snow[2 * i + 1] = s1[i];
			snow[2 * length] = '\0';
			for (int i = 0; i < length; ++i) {
				s1[i] = snow[i];
				s2[i] = snow[i + length];
			}
			ans++;
			if (path[snow] == 1)break;
			else if (path[snow] == 2) {
				ans = -1; break;
			}
			else path[snow] = 2;
		}
		cnt++;
		cout << cnt << " " << ans << endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值