Shape Number (最小表示法)

题目链接

一个字符串,这个字符串的首尾是连在一起的,要求寻找一个位置,以该位置为起点的字符串的字典序在所有的字符串中中最小。

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 inline ll read(){
 5     int x = 0, f = 1; char ch = getchar();
 6     while(ch > '9' || ch < '0'){if (ch == '-') f = -1; ch = getchar();}
 7     while(ch >= '0' && ch <= '9'){ x = x*10+ch-'0'; ch = getchar();}
 8     return x*f;
 9 }
10 
11 /************************************************************************/
12 
13 const int maxn = 3e5+7;
14 char s[maxn];
15 char str[maxn];
16 
17 int minimalRepresentation(char *str)
18 {
19     int len = strlen(str);
20     int i = 0, j = 0, k = 0;
21     while(i < len && j < len && k < len){
22         if(k == len) break;
23         if(i == j) j++;
24         int ni = i+k, nj = j+k;
25         if(ni >= len) ni -= len;
26         if(nj >= len) nj -= len;
27         if(str[ni] > str[nj]){
28             i += k+1;
29             k = 0;
30         }
31         else if( str[ni] < str[nj]){
32             j += k+1;
33             k = 0;
34         }
35         else k++;
36     }
37     return i;
38 }
39 
40 int main(){
41     while(~scanf("%s", s)){
42         int n = strlen(s);
43         for(int i = 0;i < n;i++){
44             if(i == n-1){
45                 str[i] = (((s[0] - '0') + 8 - (s[i] - '0')) % 8) + '0';
46             }
47             else {
48                 str[i] = (((s[i+1] - '0') + 8 - (s[i] - '0')) % 8) + '0';
49             }
50         }
51         int Start = minimalRepresentation(str);
52         for(int i = 0;i < n;i++){
53             printf("%c", str[(Start + i) % n]);
54         }
55         printf("\n");
56     }
57     return 0;
58 }

猜你喜欢

转载自www.cnblogs.com/ouyang_wsgwz/p/9888994.html
今日推荐