String Problem
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4568 Accepted Submission(s): 1851
Problem Description
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.
Input
Each line contains one line the string S with length N (N <= 1000000) formed by lower case letters.
Output
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.
Sample Input
abcder
aaaaaa
ababab
Sample Output
1 1 6 1
1 6 1 6
1 3 2 3
Author
WhereIsHeroFrom
Source
HDOJ Monthly Contest – 2010.04.04
#include <bits/stdc++.h>
using namespace std;
const int mn = 1000010;
char ch[mn];
int len;
int nx[mn];
void cal_next(char b[])
{
nx[0] = -1;
int k = -1;
for (int i = 1; i < len; i++)
{
while (k > -1 && b[k + 1] != b[i])
k = nx[k];
if (b[k + 1] == b[i])
k++;
nx[i] = k;
}
}
/// 单字符串的最小表示法
/// 找到以i或j开头的最小字典序的长度为len的串,返回起始位
int cal_Min()
{
int i = 0, j = 1, k = 0;
while (i < len && j < len && k < len)
{
char a = ch[(i + k) % len];
char b = ch[(j + k) % len];
if (a == b)
k++;
else
{
if (a > b)
i = i + k + 1;
else
j = j + k + 1;
k = 0;
if (i == j)
j++;
}
}
return i < j ? i : j;
}
int cal_Max()
{
int i = 0, j = 1, k = 0;
while (i < len && j < len && k < len)
{
char a = ch[(i + k) % len];
char b = ch[(j + k) % len];
if (a == b)
k++;
else
{
if (a > b) /// 改最大表示法
j = j + k + 1;
else
i = i + k + 1;
k = 0;
if (i == j)
j++;
}
}
return i < j ? i : j;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("C:\\in.txt", "r", stdin);
#endif // ONLINE_JUDGE
while (~scanf("%s", ch))
{
len = strlen(ch);
int Min = cal_Min();
int Max = cal_Max();
cal_next(ch);
int jie = len - (nx[len - 1] + 1);
int cur = 1;
if (len % jie == 0) // 整循环
cur = len / jie;
printf("%d %d %d %d\n", Min + 1, cur, Max + 1, cur);
}
return 0;
}