hdu3374 String Problem(最小最大表示法+KMP)

来源:互联网 发布:趋势买卖指标源码 编辑:程序博客网 时间:2024/05/17 06:02

最小表示法PPT

hdu3374题目

更简洁的代码

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
abcderaaaaaaababab
 
Sample Output
1 1 6 11 6 1 61 3 2 3
#include<stdio.h>#include<iostream>#include<string.h>using namespace std;char s[2000009],t[1000009];int next[1000009],len;void getnext(){    int i=0,j=-1;    next[0]=-1;    while(i<len)    {        if(j==-1||s[i]==s[j])next[++i]=++j;        else j=next[j];    }}int main(){    int m1,m2,ans,i,j,q,p;    while(scanf("%s",s)!=EOF)    {        len=strlen(s);        getnext();       if(len%(len-next[len])==0)ans=len/(len-next[len]);       else ans=1;       len=len/ans; //循环节长度       s[len]=0;       strcpy(t,s);       strcat(s,t);  //字符串增长一倍       for(p=0,q=1;p<len,q<len;)       {           if(s[p]<s[q])q++;           else              if(s[p]>s[q])p++;               else               {                   for(i=1;i<len;i++)                    if(s[p+i]>s[q+i]){ p=p+i+1;break;}                    else                        if(s[p+i]<s[q+i]){ q+=i+1;break;}                    if(i==len)break;               }               if(p==q)q++;       }       for(m1=0,m2=1;m1<len,m2<len;)       {           if(s[m1]>s[m2])m2++;           else              if(s[m1]<s[m2])m1++;               else               {                   for(i=1;i<len;i++)                    if(s[m1+i]<s[m2+i]){ m1=m1+i+1;break;}                    else                        if(s[m1+i]>s[m2+i]){ m2+=i+1;break;}                    if(i==len)break;               }               if(m1==m2)m2++;       }      printf("%d %d %d %d\n",min(p,q)+1,ans,min(m1,m2)+1,ans);    }    return 0;}
原创粉丝点击