【题解】HDU-3374 String Problem

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.

样例输入

1
2
3
abcder
aaaaaa
ababab

样例输出

1
2
3
1 1 6 1
1 6 1 6
1 3 2 3

提示

思路

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

代码

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
char s[mxn];
int nxt[mxn];

void getnxt(char* t, int m)
{
int i = 0, j = -1; nxt[0] = -1;
while (i < m)
{
if (j == -1 || t[i] == t[j]) {
i++, j++;
// if (t[i] == t[j])
// nxt[i] = nxt[j]; // next数组优化
// else
nxt[i] = j;
} else
j = nxt[j];
}
}

int KMP(char* s, char* t, int n, int m)
{
int i = 0, j = 0, ans = 0;
while (i < n)
{
if (j == -1 || s[i] == t[j]) {
i++, j++;
if (j >= m) { // 匹配
ans++;
j = nxt[j];
// return i-j;
}
} else
j = nxt[j];
}
return ans;
// return -1;
}

int getmin(char* s, int n, int cd) // cd 0:最小 1:最大
{
int i=0, j=1, k=0;
while(i<n && j<n && k<n)
{
if(s[(i+k)%n] == s[(j+k)%n]){
k++;
}else{
if((s[(i+k)%n] > s[(j+k)%n]) ^ cd)
i+=k+1;
else
j+=k+1;
k = 0;
if(i == j) i++;
}
}
return min(i, j);
}

int main()
{
while(~scanf("%s", s))
{
int sl = strlen(s);
int id1 = getmin(s, sl, 0); // 最小表示
int id2 = getmin(s, sl, 1); // 最大表示

for(int i=0; i<sl; i++) s[i+sl] = s[i];
s[sl+sl] = '\0';

getnxt(s+id1, sl);
int ans1 = KMP(s, s+id1, sl+sl-1, sl);

getnxt(s+id2, sl);
int ans2 = KMP(s, s+id2, sl+sl-1, sl);

printf("%d %d %d %d\n", id1+1, ans1, id2+1, ans2);
}
return 0;
}
_/_/_/_/_/ EOF _/_/_/_/_/