Minimum String Representation
The first letter minimum represents the original string.
The idea is:
1. pre-process, copy twice the original string as the new string, for example, str = "abc" to str = "abcabc"
2. Take the double pointers p1 and p2. p1 initially points to the first character of the new string, and p2 points to the second character.
3. First find the shift k, so that str [p1 + k]! = Str [p2 + k], and compare str [p1 + k] and str [p2 + k],
If str [p1 + k]> str [p2 + k], update p1 + = k + 1. If p1 is moved to the same position as p2, then p1 is moved to another position; otherwise, update p2 and move p2.
Output:
1. If k is equal to the length of the original string, the cycle is homogeneous. The output is min (p1, p2)
2. If either of p1 or p2 is beyond the original string length, output the other side.
Python code:
#coding=utf-8t = input()while t: [n,s] = raw_input().split() #init point p1 = 0 p2 = 1 s = s*2 #print len(s) while True: k = 0 while s[p1+k]==s[p2+k] and k!=int(n): k+=1 if k==int(n): print min(p1,p2) break if s[p1+k]>s[p2+k]: p1+=k+1 if p1==p2:p1+=1 elif s[p1+k]
=int(n): print p2 break if p2>=int(n): print p1 break t -= 1 if t==0:break
Python may exceed the time limit. You can use c ++ to rewrite it.
C ++ code:
# Include
# Include
# Define MAXN 200010 using namespace std; int min_string (int num, char * s) {char str [MAXN]; int p1 = 0, p2 = 1, k; strcpy (str, s); strcat (s, str); while (1) {k = 0; while (s [p1 + k] = s [p2 + k] & k! = Num) k ++; if (k = num) return min (p1, p2); if (s [p1 + k]> s [p2 + k]) {p1 + = k + 1; if (p1 = p2) p1 ++;} else if (s [p1 + k]
= Num) return p2; if (p2> = num) return p1;} return-1;} int main () {int t, n; cin> t; char s [MAXN]; while (t --) {cin> n> s; cout <
Ps: the array MAXN should be opened as large as possible, and the total prompt segment error is removed ~!