Skip to main content
  1. Posts/

hdu 3746 Cyclic Nacklace (最小覆盖子串,kmp)

·1 min
Note: This article is available in Chinese only. 本文暂无英文版本。 View original

hdu 3746题目链接 题意:给定一个字符串,是一个环(首尾相连),问至少再添加多少个珠子才能使得整个串是循环的。。。

思路:一下子想到了最小覆盖子串的模型。。。我求出最小覆盖子串的长度(n-nxt[n])。然后特判下最小覆盖子串的长度等于字符串长度的情况。。。试着叫了一发。。。竟然就A了2333.。。大概是所谓的题感吧(逃

 1/* ***********************************************
 2Author :111qqz
 3Created Time :2016年08月12日 星期五 00时41分19秒
 4File Name :code/hdu/3746.cpp
 5************************************************ */
 6#include <cstdio>
 7#include <cstring>
 8#include <iostream>
 9#include <algorithm>
10#include <vector>
11#include <queue>
12#include <stack>
13#include <set>
14#include <map>
15#include <string>
16#include <cmath>
17#include <cstdlib>
18#include <deque>
19#include <ctime>
20#define fst first
21#define sec second
22#define lson l,m,rt<<1
23#define rson m+1,r,rt<<1|1
24#define ms(a,x) memset(a,x,sizeof(a))
25typedef long long LL;
26#define pi pair < int ,int >
27#define MP make_pair
28using namespace std;
29const double eps = 1E-8;
30const int dx4[4]={1,0,0,-1};
31const int dy4[4]={0,-1,1,0};
32const int inf = 0x3f3f3f3f;
33const int N=1E5+7;
34char a[N];
35int n;
36int nxt[N];
37void getnxt( char *s)
38{
39    int n = strlen(s);
40    int i = 0;
41    int j = -1;
42    nxt[0] = -1;
43    while (i<n)
44	if (j==-1||s[i]==s[j]) nxt[++i]=++j;
45	else j = nxt[j];
46}
47int main()
48{
49	#ifndef  ONLINE_JUDGE
50	freopen("code/in.txt","r",stdin);
51  #endif
52	int T;
53	cin>>T;
54	while (T--)
55	{
56	    scanf("%s",a);
57	    getnxt(a);
58	    int n =strlen(a);
59	    int k = n - nxt[n];
60	    if (k==n) printf("%d\n",n);
61	    else if (n%k==0) printf("0\n");
62		 else printf("%d\n",k-n%k);
63	}
64  #ifndef ONLINE_JUDGE
65  fclose(stdin);
66  #endif
67    return 0;
68}

Related

KMP与最小覆盖子串

·3 mins
参考资料(本文大部分是参考这篇博客,附带一些证明步骤的解释) 首先明确一些概念: 最小覆盖子串:对于某个字符串s,它的最小覆盖子串指的是长度最小的子串p,p满足通过自身的多次连接得到q,最后能够使s成为q的子串。 比如: 对于s=“abcab”,它的最小覆盖子串p=“abc”,因为p通过在它后面再接上一个p(即重叠0个字符),可以得到q=“abcabc”,此时s是q的子串。 对于s=“ababab”,它的最小覆盖子串为p=“ab”。

hdu 1841 Find the Shortest Common Superstring (kmp)

·2 mins
hdu 1841题目链接 题意:给两个字符串,问包含这两个字符串的最小的字符串的长度(最小是因为,一个串的子串可能是另一个串的后缀,这样出现一次就可以了)