CDOJ 1305 Just a Magic String

子串只有10^6,所以可以直接去匹配,不管什么规律,但是,母串要到4*10^6,才能考虑到10^6的串的所有情况,具体,用小数据列举一下就可以发现。

然后我用的是KMP,貌似暴力匹配也能过,另,正解貌似是DFS


代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
#define maxn 4194304
char s1[maxn], s2[1000003];
int then[1000003];
char idx[256];
int n1, n2;
void init_s1()
{
	idx['a'] = 'b', idx['b'] = 'a';
	s1[0] = 'a', s1[1] = 'b';
	int len = 2;
	while (len < maxn)
	{
		for (int i = 0; i < len; ++i)
			s1[len + i] = idx[s1[i]];
			
		len <<= 1;
	}
}
void get_then()
{
	int i = 0, j = -1;
	then[0] = -1;
	while (i < n2)
	{
		if (j == -1 || s2[i] == s2[j])
		{
			++i;
			++j;
			then[i] = j;
		}
		else
			j = then[j];
	}
}
int kmp()
{
	int t1 = 0, t2 = 0;
	while (t1<n1&&t2<n2)
	{
		if (t2 == -1 || s1[t1] == s2[t2])
		{
			t1++;
			t2++;
		}
		else t2 = then[t2];
	}
	if (t2 == n2)
		return t1 - t2 + 1;
	else
		return -1;
}
int main()
{
	//freopen("input.txt", "r", stdin);
	scanf("%s", s2);
	n1 = maxn, n2 = strlen(s2);
	init_s1();
	get_then();
	/*for (int i = 0; i < 10; ++i)
		printf("%c", s1[i]);*/
	int ans = kmp();
	printf("%d\n", ans);
	//system("pause");
	//while (1);
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值