POJ 3617 Best Cow Line

题目链接:

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

解题思路:

  1. 按照字典序比较S和将S反转后的字符串S‘
  2. 如果S较小,就从S的开头取出一个文字,追加到T的末尾
  3. 如果S’较小,就从S的末尾取出一个文字,追加到T的末尾

注意,题目有坑: Every line (except perhaps the last one) contains the initials of 80 cows ('A'..'Z') in the new line.

AC代码:

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

int main(){
    int n;
    while(~scanf("%d",&n)){
        string str = "";
        char x;
        for(int i = 0; i < n; i++){
            cin>>x;
            str += x;
        }
        int l = 0,r = n-1;
        int sum = 0;
        while(l <= r){
            bool flag;//表示是否取左边
            for(int i = 0; l + i <= r; i++){
                if(str[l+i] < str[r-i]){
                    flag = true;
                    break;
                }
                else if(str[l+i] > str[r-i]){
                    flag = false;
                    break;
                }
            }
            if(flag)
                putchar(str[l++]);
            else
                putchar(str[r--]);
            sum++;
            if(sum % 80 == 0){
                printf("\n");
            }
        }
    }
    return 0;
}



你可能感兴趣的:(贪心)