poj3617 Best Cow Line(贪心+字符串)

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


http://poj.org/problem?id=3617

题意:给你一个字符串,通过不断地对其进行头尾比较输出较小的构建字典序最小字符串,输出。


思路:很不错的水题,首先是贪心思想,就如挑战书上所说,将当前字符串与其反转的字符串比较,使末尾字符相等的字符串依然消除较小的。较大的字符串最后一个元素进队列,并将其消除,最后输出队列。输入输出还是用cin和cout,处理字符串还是c++牛。注意输出是每80个字符输出一空行,刚开始没看出来T T。


好久没练字符串,正好复习了下字符串和队列。本来想用string来着,好像比较麻烦,还是不熟练啊。。



#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <queue>
#include <iostream>

using namespace std;

typedef long long ll;
const int N = 2005;

int main()
{
  //  freopen("in.txt", "r", stdin);
    int n;
    char s[N], maxs[N];
    while(~scanf("%d", &n))
    {
        queue<char>que;
        for(int i = 0; i < n; i++)
            cin >> s[i];
        s[n] = '\0';
        memcpy(maxs, s, sizeof(s));
        int len = strlen(maxs);
        char tmp1[N], tmp2[N];
        while(len!=0)
        {
            memset(tmp1, 0, sizeof(tmp1));
            memset(tmp2, 0, sizeof(tmp2));
            strcpy(tmp1, maxs);
            strcpy(tmp2, maxs);
            reverse(tmp2, tmp2+len);
            if(strcmp(tmp2, tmp1)>0) strcpy(maxs, tmp2);//与反转后的字符串比较,选出较大的,注意要判断大于0.
            else if(strcmp(tmp1, tmp2)>0) strcpy(maxs, tmp1);
            que.push(maxs[len-1]);//字符串较大的末尾元素较小,入队列
            maxs[len-1] = '\0';
            len--;
        }
        int cnt = 1;
        while(!que.empty())
        {
            cout << que.front();
            que.pop();
            if(cnt%80==0) printf("\n");
            cnt++;
        }
    }
}


猜你喜欢

转载自blog.csdn.net/Flynn_curry/article/details/62228314