ZOJ 1729

字符串最小表示 模板

#include<bits/stdc++.h>
using namespace std;

const int maxn = 1e5+10;

int MinRepresentation(const char *s, int len){
    int i, j, k;
    i = k = 0;
    j = 1;
    while(i < len && j < len){
        k = 0;
        while(k < len && s[i+k] == s[j+k]) k++;
        if (k == len) return i;
        if (s[i+k] > s[j+k]) i = i+k+1;
        else j = j+k+1;
        if (i == j) j++;
    }
    return min(i, j);
}

char s[maxn*2], tmp[maxn];

int main(){
    int n;
    std::ios::sync_with_stdio(false);
    cin >> n;
    while(n--){
        int len;
        cin >> len >> s;
        strncpy(tmp, s, len);
        strcat(s, tmp);
        cout << MinRepresentation(s, len) << endl;
    }

    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章