Shuffle'm Up POJ - 3087 模拟

题解

先将ab串交叉合并在一起作为一个2n长度的串,并记录下来。每次将串拆分为两半再次进行交叉合并,如果变成目标串则成功,如果回到最开始的记录则失败。
直接模拟即可,使用string类可以方便的进行拆分和合并。

AC代码

#include <stdio.h>
#include <iostream>
#include <string>
#define fst first
#define sed second
using namespace std;
typedef long long ll;

const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
char buf[210];
int n;
string a, b, c, d, t;

void merge() //ab合并到t
{
	t.clear();
	for (int i = 0; i < n; ++i)
	{
		t.push_back(b[i]);
		t.push_back(a[i]);
	}
}
void split()
{
	a = t.substr(0, n);
	b = t.substr(n);
}
int solve()
{
	merge();
	if (t == c)
		return 1;
	int cnt = 1;
	d = t; //记录
	do 
	{
		++cnt;
		split();
		merge();
		if (t == c)
			return cnt;
	} while (t != d);
	return -1;
}
int main()
{
#ifdef LOCAL
	freopen("C:/input.txt", "r", stdin);
#endif
	int T;
	cin >> T;
	for (int ti = 1; ti <= T; ++ti)
	{
		scanf("%d", &n);
		scanf("%s", buf);
		a = buf;
		scanf("%s", buf);
		b = buf;
		scanf("%s", buf);
		c = buf;
		printf("%d %d\n", ti, solve());
	}

	return 0;
}

猜你喜欢

转载自blog.csdn.net/CaprYang/article/details/88920773