码迷,mamicode.com
首页 > 其他好文 > 详细

ZOJ 4010 Neighboring Characters(ZOJ Monthly, March 2018 Problem G,字符串匹配)

时间:2018-03-11 21:09:54      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:...   等价   get   区间   typedef   efi   方案   gpo   ref   

题目链接  ZOJ Monthly, March 2018 Problem G

题意  给定一个字符串。现在求一个下标范围$[0, n - 1]$的$01$序列$f$。$f[x] = 1$表示存在一种方案,删掉原字符串中的连续$x$个字母,

   使得剩下的字符串中任意相邻的两个字母都不同。在这道题中所有的字符串首位字符看做是相邻的。

 

对于每个起始位置求出最多往右延伸到的位置,满足该区间代表的字符串是一个满足任意相邻字母不同的字符串。

首先考虑一个连续的满足任意相邻字母不同的字符串。设其长度为$l$

$i$从$1$枚举到$l$,判断能否删掉连续$n - i$个字母(剩下$i$个字母)满足题意。(对当前字符串来说$i > l$显然无法满足)

对于任意的一种删掉连续$n - i$个字母的方案,剩下的$i$个字母组成的字符串已经满足了任意相邻两个字母不同,

但是还不一定不满足首尾字母不同。

所以如果满足以下任意一个条件

$s[1]$ $\neq$ $s[i]$

$s[2]$ $\neq$ $s[i+1]$

$s[3]$ $\neq$ $s[i+2]$

...

$s[l-i+1]$ $\neq$ $s[l]$

其实这个东西等价于$s[1..l-i+1]$ $\neq$ $s[i..l]$,那么直接用字符串hash判断即可。

时间复杂度$O(n)$

 

#include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b)	for (int i(a); i <= (b); ++i)
#define dec(i, a, b)	for (int i(a); i >= (b); --i)

typedef unsigned long long LL;

const int N = 2e6 + 10;
const LL base = 20123;

int T;
int n, m;
int ans[N];
char s[N];
LL bin[N], h[N];
LL seed = 1;

inline LL gethash(int l, int r){ return h[r] - h[l - 1] * bin[r - l + 1]; }

int main(){

	bin[0] = 1;
	rep(i, 1, 2e6 + 1) bin[i] = bin[i - 1] * base;

	scanf("%d", &T);
	while (T--){
		scanf("%s", s + 1);
		n = strlen(s + 1);
		m = 2 * n - 1;

		rep(i, 1, n - 1) s[i + n] = s[i];
		h[0] = 0; rep(i, 1, m) h[i] = h[i - 1] * base + s[i];

		memset(ans, 0, sizeof ans);
		for (int i = 1, j; i < m; i = j + 1){
			for (j = i; j < m && s[j] != s[j + 1]; ) ++j;
			int l = j - i + 1;
			rep(k, 2, l){
				if (k > n) break;
				if (gethash(i, i + l - k) != gethash(j - l + k, j)) ans[n - k] = 1;
			}
		}

		rep(i, 0, n - 2) putchar(ans[i] + 48); putchar(49);
		putchar(10);		
	}
	return 0;
}

 

  

 

ZOJ 4010 Neighboring Characters(ZOJ Monthly, March 2018 Problem G,字符串匹配)

标签:...   等价   get   区间   typedef   efi   方案   gpo   ref   

原文地址:https://www.cnblogs.com/cxhscst2/p/8545410.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!