#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e6;
char s[N];
int main()
{
scanf("%s", s + 1);
//下标从1开始
int n = strlen(s + 1);
//复制自身拼接到后面
for (int i = 1; i <= n; i ++ ) s[n + i] = s[i];
//B[i],B[j]
int i = 1, j = 2, k = 0;
while (i <= n && j <= n){
//相同的字符k++
for (int k = 0; k < n && s[i + k] == s[j + k]; k ++ );
//全部相同,则i,j较小的那个是答案
if(k == n) break;
if(s[i + k] > s[j + k]) {
i = i + k + 1;
if(i == j) i++;
}else{
j = j + k + 1;
if(i == j) j ++;
}
}
int ans = min(i, j);
//B[ans]为答案
for (int i = ans; i < ans + n; i ++ ){
cout << s[i];
}
}
在acwing上好像找不到对应的题,去洛谷搜了下,这里附上题目链接 problem
代码
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e6 + 10;
int s[N];
int main()
{
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i ++ ){
scanf("%d", &s[i]);
}
//复制自身拼接到后面
for (int i = 1; i <= n; i ++ ) s[n + i] = s[i];
//B[i],B[j]
int i = 1, j = 2, k = 0;
while (i <= n && j <= n){
//相同的字符k++
for (k = 0; k < n && s[i + k] == s[j + k]; k ++ );
//全部相同,则i,j较小的那个是答案
if(k == n) break;
if(s[i + k] > s[j + k]) {
i = i + k + 1;
if(i == j) i++;
}else{
j = j + k + 1;
if(i == j) j ++;
}
}
int ans = min(i, j);
//B[ans]为答案
for (int i = ans; i < ans + n; i ++ ){
printf("%d ", s[i]);
}
}