PKU 1509 Glass Beads

字符串最小表示:

 

  
    
#include < stdio.h >
#include
< string .h >
int min( int a, int b)
{
if (a < b) return a;
else return b;
}
int main()
{
char str[ 10001 ],s[ 20002 ];
int k,p1,p2,len;
int T,ans;
scanf(
" %d " , & T);
while (T -- )
{
scanf(
" %s " ,str);
len
= strlen(str);
memset(s,
' \0 ' , sizeof (s));
strcpy(s,str);
strcpy(s
+ len,str);
p1
= 0 ,p2 = 1 ,k = 0 ;
while ( 1 )
{
if (s[p1 + k] == s[p2 + k])
{
k
++ ;
if (k == len)
{
ans
= min(p1,p2);
break ;
}
}
else if (s[p1 + k] > s[p2 + k])
{
p1
= p1 + k + 1 ;
k
= 0 ;
if (p1 == p2) p1 ++ ;
}
else
{
p2
= p2 + k + 1 ;
k
= 0 ;
if (p2 == p1) p2 ++ ;
}
if (p1 >= len)
{
ans
= p2;
break ;
}
if (p2 >= len)
{
ans
= p1;
break ;
}
}
printf(
" %d\n " ,ans + 1 );
}
return 0 ;
}

 

你可能感兴趣的:(pku)