AcWing 158. 项链 (最小表示法,字符串)

闫总的代码,稍微改了改,注释了很多东西

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<char, int> PII;
const int mod = 1e9 + 7;
const int INF = 0x3f3f3f3f;
const int N = 1e6 + 50;

int n;
char a[N], b[N];

int get_min(char s[])
{
    
    
    int i = 0, j = 1;
    while (i < n && j < n) {
    
     // 剩下的一定是最优的 if while (true) 
        int k = 0;           //                          |
                                                //       v
                               //      越界  -----------------

        while (k < n && s[i + k] == s[j + k])
            k++;
        if (k == n) {
    
    
            cout << "dddd" << endl;break;
        }
            
        if (s[i + k] > s[j + k])
            i += k + 1;
        else
            j += k + 1;
        if (i == j)
            j++;
        cout << i << ' ' << j << endl;
    }
    int k = min(i, j); // 也是防止越界
    s[k + n] = 0;
    return k;
}

int main()
{
    
    
    scanf("%s", a);
    n = strlen(a);
    memcpy(a + n, a, n);

    int x = get_min(a);

    cout << a + x << endl;


    // if (strcmp(a + x, b + y))
    //     puts("No");
    // else {
    
    
    //     puts("Yes");
    //     puts(a + x);
    // }

    return 0;
}

おすすめ

転載: blog.csdn.net/YingShen_xyz/article/details/117046783
158