poj 3617 Best Cow Line(贪心)

来源:互联网 发布:excel如何删除一列数据 编辑:程序博客网 时间:2024/05/28 15:09

poj 3617 Best Cow Line (贪心)

题目链接:http://poj.org/problem?id=3617

题目意思:给出一条长度为n的字符串S,目标是要构造一条字典序尽量小,长度为n的字符串T。构造的规则是,如果S的头部的字母 < S的尾部的字母,那么将S的头部的字母加入到T中,删除S的头部的字母;如果S的头部的字母 > S的尾部的字母,那么将S的尾部的字母加入到T中,删除S的尾部的字母。

   这个题目的关键是如何处理 S 的头部的字母(假设用 i 指示) = S的尾部的字母(j) 这种情况。此时需要比较 i+1 和 j-1 的位置的字母,如果相同,继续比较下去。

#include <iostream>#include <cstdio>#include <cstdlib>using namespace std;const int maxn = 2000 + 10;char s[maxn];int main(){    int n, i, a, b;    while (scanf("%d", &n) != EOF)    {        for (i = 0; i < n; i++)        {            getchar();            scanf("%c", &s[i]);        }        int cnt = 0;        a = 0, b = n-1;        while (a <= b)        {            bool left = false;            for (i = 0; a + i <= b; i++)            {                if (s[a+i] < s[b-i])                {                    left = true;                    break;                }                else if (s[a+i] > s[b-i])                {                    left = false;                    break;                }            }            if (left)                printf("%c", s[a++]);            else                printf("%c", s[b--]);            cnt++;            if (cnt % 80 == 0)                putchar('\n');        }    }    return 0;}


0 0
原创粉丝点击