String Problem
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
题意:循环移位,一直移到尾变成头,对于中间的出现的情况,在里面找字典序最小的和字典序最大的下标标号,然后把其对应次数也输出来。
分析:
循环移位的次数显然是最小循环节的最大周期数,套一个最大和最小表示法就ok了。
#include<cstdio>
#include<iostream>
#include<fstream>
#include<algorithm>
#include<functional>
#include<cstring>
#include<string>
#include<cstdlib>
#include<iomanip>
#include<numeric>
#include<cctype>
#include<cmath>
#include<ctime>
#include<queue>
#include<stack>
#include<list>
#include<set>
#include<map>
using namespace std;const int N = 1000002;
int nxt[N];
int k;
void getnxt(char T[],int tlen)
{int j, k;j = 0; k = -1;nxt[0] = -1;while(j < tlen){if(k == -1 || T[j] == T[k]){nxt[++j] = ++k;if (T[j] != T[k]) nxt[j] = k; } elsek = nxt[k];}
}
//最小表示法
int get_minstring(char *s)
{int len = strlen(s);int i = 0, j = 1, k = 0;while(i<len && j<len && k<len){int t=s[(i+k)%len]-s[(j+k)%len];if(t==0)k++;else{if(t > 0)i+=k+1;elsej+=k+1;if(i==j) j++;k=0;}}return min(i,j);
}//最大表示法
int get_maxstring(char *s)
{int len = strlen(s);int i = 0, j = 1, k = 0;while(i<len && j<len && k<len){int t=s[(i+k)%len]-s[(j+k)%len];if(t==0)k++;else{if(t > 0)j+=k+1;elsei+=k+1;if(i==j) j++;k=0;}}return min(i,j);
}
char str[N];
int main()
{while(scanf("%s",str)!=EOF){int len = strlen(str);getnxt(str,len);int tt = len - nxt[len];int num = 1;if(len%tt == 0){num = len/tt;}int posmin = get_minstring(str);int posmax = get_maxstring(str);printf("%d %d %d %d\n",posmin+1,num,posmax+1,num);}return 0;
}