UVa 1584 Circular Sequence --- 水题

 

  UVa 1584

  题目大意:给定一个含有n个字母的环状字符串,可从任意位置开始按顺时针读取n个字母,输出其中字典序最小的结果

  解题思路:先利用模运算实现一个判定给定一个环状的串以及两个首字母位置,比较二者字典序大小的函数,

       然后再用一层循环,进行n次比较,保存最小的字典序的串的首字母位置,再利用模运算输出即可

/* UVa 1584 Circular Sequence --- 水题 */
#include <cstdio>
#include <cstring>

//字符串s为环状,p q为起始位置 长度都为n, 判断 p 是否小于 q
int less(const char* s, int p, int q){
    int len = strlen(s);
    for (int i = 0; i < len; ++i){
        if (s[(p + i) % len] > s[(q + i) % len]){
            return -1;//p > q
        }
        else if (s[(p + i) % len] < s[(q + i) % len]){
            return 1;// q < q
        }
    }
    return 0; //相等
}

int main()
{
    char s[105];
    int t;
    scanf("%d", &t);
    while (t--){
        scanf("%s", s);
        int ans = 0;
        int len = strlen(s);
        //相当于有n个串进行比较 挑出字典序最小的
        for (int i = 1; i < len; ++i){
            if (less(s, i, ans) == 1){
                ans = i;
            }
        }
        //经过循环的选择 ans已经保存字典序最小的串的第一个字符的位置
        for (int i = 0; i < len; ++i){
            printf("%c", s[(ans + i) % len]);
        }
        printf("\n");


    }//while(t)

    return 0;
}
View Code

 

posted @ 2016-03-24 01:32  tan90丶  阅读(465)  评论(0编辑  收藏  举报