String Problem(HDU-3374)

题面

Give you a string with length N, you can generate N strings by left shifts. For example let consider the string “SKYLONG”, we can generate seven strings: String Rank SKYLONG 1 KYLONGS 2 YLONGSK 3 LONGSKY 4 ONGSKYL 5 NGSKYLO 6 GSKYLON 7 and lexicographically first of them is GSKYLON, lexicographically last is YLONGSK, both of them appear only once. Your task is easy, calculate the lexicographically fisrt string’s Rank (if there are multiple answers, choose the smallest one), its times, lexicographically last string’s Rank (if there are multiple answers, choose the smallest one), and its times also.

输入

Each line contains one line the string S with length N (N <= 1000000) formed by lower case letters.

输出

Output four integers separated by one space, lexicographically fisrt string’s Rank (if there are multiple answers, choose the smallest one), the string’s times in the N generated strings, lexicographically last string’s Rank (if there are multiple answers, choose the smallest one), and its times also.

样例输入

1abcder
2aaaaaa
3ababab

样例输出

11 1 6 1
21 6 1 6
31 3 2 3

提示

思路

先用最小表示法,求出最大最小字典序的子串,然后跑KMP。

代码

 1char s[mxn];
 2int nxt[mxn];
 3
 4void getnxt(char* t, int m)
 5{
 6    int i = 0, j = -1; nxt[0] = -1;
 7    while (i < m)
 8    {
 9        if (j == -1 || t[i] == t[j]) {
10            i++, j++;
11            // if (t[i] == t[j])
12            //     nxt[i] = nxt[j]; // next数组优化
13            // else
14                nxt[i] = j;
15        } else
16            j = nxt[j];
17    }
18}
19
20int KMP(char* s, char* t, int n, int m)
21{
22    int i = 0, j = 0, ans = 0;
23    while (i < n)
24    {
25        if (j == -1 || s[i] == t[j]) {
26            i++, j++;
27            if (j >= m) {   // 匹配
28                ans++;
29                j = nxt[j];
30                // return i-j;
31            }
32        } else
33            j = nxt[j];
34    }
35    return ans;
36    // return -1;
37}
38
39int getmin(char* s, int n, int cd) // cd 0:最小 1:最大
40{
41    int i=0, j=1, k=0;
42    while(i<n && j<n && k<n)
43    {
44        if(s[(i+k)%n] == s[(j+k)%n]){
45            k++;
46        }else{
47            if((s[(i+k)%n] > s[(j+k)%n]) ^ cd)
48                i+=k+1;
49            else
50                j+=k+1;
51            k = 0;
52            if(i == j) i++;
53        }
54    }
55    return min(i, j);
56}
57
58int main()
59{
60    while(~scanf("%s", s))
61    {
62        int sl = strlen(s);
63        int id1 = getmin(s, sl, 0); // 最小表示
64        int id2 = getmin(s, sl, 1); // 最大表示
65
66        for(int i=0; i<sl; i++) s[i+sl] = s[i];
67        s[sl+sl] = '\0';
68
69        getnxt(s+id1, sl);
70        int ans1 = KMP(s, s+id1, sl+sl-1, sl);
71
72        getnxt(s+id2, sl);
73        int ans2 = KMP(s, s+id2, sl+sl-1, sl);
74
75        printf("%d %d %d %d\n", id1+1, ans1, id2+1, ans2);
76    }
77    return 0;
78}