Advanced Guide to Algorithm Competition---0x18 (Minimal Notation) Necklace

Topic

Insert picture description here

answer

  1. For two identical strings, we can directly compare whether the strings with the smallest lexicographic order are equal. To find the smallest lexicographic order, use the smallest notation O(n) directly.
  1. Minimal notation explanation: -> click here

Code

#include <cstring>
#include <iostream>
#include <algorithm>
#include <string.h>

using namespace std;

const int N = 2000000;

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

int get_min(char str[]) {
    
    
    int i = 0, j = 1;
    while (i < n && j < n) {
    
    
        int k = 0;
        while (k < n && str[i + k] == str[j + k]) k++;
        if (k == n) break;
        if (str[i + k] > str[j + k]) i += k + 1;
        else j += k + 1;
        if (i == j) i++;
    }
    int res = min(i, j);
    str[res + n] = 0;
    return res;
}

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

    memcpy(a + n, a, n);
    memcpy(b + n, b, n);

    int ia = get_min(a), ib = get_min(b);

    if (strcmp(a + ia, b + ib)) puts("No");
    else {
    
    
        puts("Yes");
        puts(a + ia);
    }

    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44791484/article/details/113934369