2019牛客暑期多校训练营(第七场)A String (字符串的最小表示)

思路

这题思路如果是递归的话,应该是比较正确的。但是实际上只用切割两次就可以了。
先把原串从后向前切割一次,再把每一部分切割一次。
切两次的思路实际上是有漏洞的。
递归的思路,终点是,如果串长为1,或者串的最小表示在0的位置。

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

char str[210];
bool loc[210];
char s[210];

int getmin(char *s, int n)
{
    int i = 0, j = 1, k = 0;
    while(i < n && j < n && k < n)
    {
        int t = s[(i + k) % n] - s[(j + k) % n];
        if(!t) k++;
        else
        {
            if(t > 0) i += k + 1;
            else j += k + 1;
            if(i == j) j++;
            k = 0;
        }
    }
    return i < j ? i : j;
}


int main()
{
    int T;
    scanf("%d",&T);
    while (T--) {
        scanf("%s",str);
        memset(loc,0,sizeof(loc));
        int tmp=0,len=strlen(str);
        while ((tmp=getmin(str,len))!=0) {
            loc[tmp]=true;
            int cnt=0;
            for (int i=tmp;i<len;i++) {
                s[cnt++]=str[i];
            }
            s[cnt]='\0';
            int stmp=0;
            while ((stmp=getmin(s,cnt))!=0) {
                loc[tmp+stmp]=true;
                cnt=stmp;
            }
            len=tmp;
        }
        len=strlen(str);
        for (int i=0;i<len;i++) {
            if (loc[i]) {
                printf(" ");
            }
            printf("%c",str[i]);
        }
        puts("");
    }
    return 0;
}

posted @ 2019-08-14 10:41  xyee  阅读(125)  评论(0编辑  收藏  举报