String Problem hdu 3374 最小表示法加KMP的next数组

String Problem

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1492    Accepted Submission(s): 662


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
 
 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <algorithm>
 4 #include <string.h>
 5 #include <set>
 6 using namespace std;
 7 char s[1100000];
 8 int next[1100000];
 9 int get(char s[],int flag,int l)
10 {
11     int i,j,k,t;
12     i=k=0;
13     j=1;
14     while(i<l&&j<l&&k<l)
15     {
16          t=s[(i+k>=l?i+k-l:i+k)]-s[(j+k>=l?j+k-l:j+k)];
17         if(!t)k++;
18         else
19         {
20             if(!flag)
21             {
22                 if(t>0)i+=k+1;
23                 else j+=k+1;
24             }
25             else
26             {
27                 if(t<0)i+=k+1;
28                 else j+=k+1;
29             }
30             if(i==j)j++;
31             k=0;
32         }
33     }
34     return i;
35 }
36 void getsnext(char s[],int l)
37 {
38     int i=1,j=0;
39     next[0]=0;
40     while(i<l)
41     {
42         if(j==0||s[i]==s[j])
43         {
44             i++,j++;
45             next[i]=j;
46         }
47         else j=next[j];
48     }
49     next[l-1]++;
50 }
51 int main()
52 {
53     while(~scanf("%s",s))
54     {
55         int l=strlen(s);
56         int minaa=get(s,0,l);
57         int maxaa=get(s,1,l);
58         getsnext(s,l);
59         cout<<minaa+1<<" "<<((l%(l-next[l-1]))?1:l/(l-next[l-1]));
60         cout<<" "<<maxaa+1<<" ";
61         cout<<((l%(l-next[l-1]))?1:l/(l-next[l-1]))<<endl;
62     }
63 }
View Code
 
 
原文地址:https://www.cnblogs.com/ERKE/p/3833062.html