返回顶部

KMP

 

 

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <cstdlib>
 4 #include <iostream>
 5 #include <set>
 6 #include <map>
 7 #include <queue>
 8 #include <vector>
 9 #include <utility>
10 #include <algorithm>
11 #define MAXN 8005
12 #define INF 0x3f3f3f3f
13 #define DEBUG
14 #define DataIn
15 typedef long long LL;
16 
17 using namespace std;
18 int nex[MAXN];
19 char s[MAXN];
20 int len;
21 int dp[MAXN];
22 int a[MAXN][MAXN];
23 
24 
25 void prekmp(char x[])
26 {
27     int i = 0, j = -1;
28     nex[0] = -1;
29     while(i < len)
30     {
31 //        while(j!=-1 && x[i]!=x[j])
32 //            j = nex[j];
33 //        nex[++i] = ++j;
34         if(j == -1 || x[i] == x[j])
35             nex[++i] = ++j;
36         else
37             j = nex[j];
38     }
39     for(int i=0;i<=len;i++)cout<<nex[i]<<" ";cout<<endl;
40 }
41 int digitcnt(int k)
42 {
43     int cnt = 0;
44     while(k)
45     {
46         k /= 10;
47         cnt++;
48     }
49     return cnt;
50 }
51 
52 void init()
53 {
54     for(int i = 0; i < len; i++)
55     {
56         prekmp(s + i);
57         for(int j = i; j < len; j++)
58         {
59             int t1 = j - i + 1, t2 = t1 - nex[t1];
60             a[i][j] = t1 % t2 == 0 ? t2 + digitcnt(t1/t2) : t1 + 1;
61         }
62     }
63 }
64 
65 int main()
66 {
67     scanf("%s", s);
68     len = strlen(s);
69     fill(dp, dp+len, INF);
70     init();
71     dp[0] = 2;
72     for(int i = 1; i < len;i ++)
73     {
74         dp[i] = a[0][i];
75         for(int j = 0; j < i; j ++)
76             dp[i] = min(dp[i],dp[j] + a[j + 1][i]);
77     }
78     for(int i=0;i<len;i++)cout<<dp[i]<<endl;
79     printf("%d\n",dp[len-1]);
80     return 0;
81 }
View Code

 

posted @ 2018-11-13 18:31  牛奶加咖啡~  阅读(87)  评论(0编辑  收藏  举报