zoukankan      html  css  js  c++  java
  • ZOJ 4010 Neighboring Characters(ZOJ Monthly, March 2018 Problem G,字符串匹配)

    题目链接  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]$ $ eq$ $s[i]$

    $s[2]$ $ eq$ $s[i+1]$

    $s[3]$ $ eq$ $s[i+2]$

    ...

    $s[l-i+1]$ $ eq$ $s[l]$

    其实这个东西等价于$s[1..l-i+1]$ $ eq$ $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;
    }
    

      

  • 相关阅读:
    BZOJ5212 ZJOI2018历史(LCT)
    BZOJ5127 数据校验
    253. Meeting Rooms II
    311. Sparse Matrix Multiplication
    254. Factor Combinations
    250. Count Univalue Subtrees
    259. 3Sum Smaller
    156. Binary Tree Upside Down
    360. Sort Transformed Array
    348. Design Tic-Tac-Toe
  • 原文地址:https://www.cnblogs.com/cxhscst2/p/8545410.html
Copyright © 2011-2022 走看看