poj 3087 Shuffle'm Up

简单的模拟题, 据说可以用map水过, 不过想学一下字符串hash,写了一发hash, 奇丑无比。。。


#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>

using namespace std;
typedef unsigned long long ll;

const int HASH = 10007;
const int MAXN = 1010;
const int SEED = 131;
int Hash[HASH];
char s1[MAXN];
char s2[MAXN];
char s3[MAXN * 2];

ll getHash(char * str) {
	ll hash = 0;
	while (*str) {
		hash = hash * SEED + (*str++);	
	}
	return hash % HASH;
}

int main() {
	
	int t;
	scanf("%d", &t);
	int CASE = 1;
	while (t--) {
		memset(Hash, 0, sizeof(Hash));
		int n; 
		scanf("%d", &n);
		scanf("%s%s%s", s1, s2, s3);
		ll end = getHash(s3);
		int ans = 0;
		int flag = 0;

		while (1) {
			ans ++;	
			for (int i = 0; i < n; i++) {
				s3[i * 2] = s2[i];
				s3[i * 2 + 1] = s1[i];
			}s3[2 * n] = 0;

			ll tmp = getHash(s3);
			if (tmp == end) {
				flag = 1;
				break;
			}
			if (Hash[tmp] == 0) 
				Hash[tmp] = 1;
			else 
				break;

			for (int i = 0; i < n; i++) 
				s1[i] = s3[i];
			s1[n] = 0;
			for (int i = n; i < n * 2; i++)
				s2[i - n] = s3[i];
			s2[n] = 0;
		}
		printf("%d ", CASE++);

		if (flag)
			printf("%d\n", ans);
		else 
			printf("-1\n");
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值