poj3617Best Cow Line(贪心)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/readlnh/article/details/52234432

题意

给定长度为n的串s,要构造一个长度为n的新串t,求字典序最小的t。每次操作可以把s的头或者尾那个字符加到t的尾部,t一开始是空字符串。

思路

很明显的贪心,要使字典序最小,明显每次添加的字符要尽量小。不过,这样子还存在一个问题。比如s为:abbca,这种情况下,显然要把s的首位置那个a加入t才能使字典序最小,所以遇到头尾相同的情况需要看看后面位置的字符大小情况。还有一点,这题80个字符一行输出,看题要仔细。。。感谢讨论区

代码

#include <cstdio>
#include <iostream>
using namespace std;

char a[2000 + 10];

int main() {
    int n;
    while(~scanf("%d", &n)) {
        int l = 0;
        int r = n - 1;
        for(int i = 0; i < n; i++) {
            getchar();
            a[i] = getchar();
        }
        int num_char = 0;
        while(r - l >= 0) {
            int ll = l;
            int rr = r;
            while(a[ll] == a[rr]) {
                ll++;
                rr--;
            }
            if(a[ll] < a[rr]) {
                printf("%c", a[l]);
                l++;
            }
            else if(a[ll] > a[rr]) {
                printf("%c", a[r]);
                r--;
            }
            num_char++;
            if(num_char % 80 == 0)
                printf("\n");
        }
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/readlnh/article/details/52234432
今日推荐