贪心POJ3617

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

FJ is about to take his N (1 ≤ N ≤ 2,000) cows to the annual"Farmer of the Year" competition. In this contest every farmer arranges his cows in a line and herds them past the judges.

The contest organizers adopted a new registration scheme this year: simply register the initial letter of every cow in the order they will appear (i.e., If FJ takes Bessie, Sylvia, and Dora in that order he just registers BSD). After the registration phase ends, every group is judged in increasing lexicographic order according to the string of the initials of the cows' names.

FJ is very busy this year and has to hurry back to his farm, so he wants to be judged as early as possible. He decides to rearrange his cows, who have already lined up, before registering them.

FJ marks a location for a new line of the competing cows. He then proceeds to marshal the cows from the old line to the new one by repeatedly sending either the first or last cow in the (remainder of the) original line to the end of the new line. When he's finished, FJ takes his cows for registration in this new order.

Given the initial order of his cows, determine the least lexicographic string of initials he can make this way.

*这题主要是用贪心,目标主要是从已知的字符串构造出字典序尽可能小的字符串
*从字典序性质来看,无论字符串末尾有多大,只要保证前面部分较小就可以咯!
*假设原来字符串为S,目标字符串为T,那么,不断取出S的开头和末尾较小的一个
*字符放到T的末尾。上面的没有针对开头与结尾相同,如果,遇到这样动情况,应
*该比较下一个字符的大小。如果,下一个字符也相同,那么可以得到下面的算法:
*按照字典序比较S和将S反转后的字符串S’
*如果,S较小,那么取出S开头字符,追加到T的末尾
*如果,S'较小,那么取出S结尾字符,追加到T的末尾
*如果,相同则再比较
#include<iostream>
using namespace std;
int n;
char oldLine[2000];
char newLine[2000];
int equal(int flag1,int flag2)
{
    if(flag1==flag2)return 0;//1都行
    if (oldLine[flag1]>oldLine[flag2])
    {
        return 0;
    }
    else if (oldLine[flag1]<oldLine[flag2])
    {
        return 1;
    }
    else
    {
        equal(flag1+1, flag2-1);
    }
}
int main()
{
    cin>>n;
    for (int i = 0; i < n; i++)
    {
        cin >> oldLine[i];
    }
    int flag1 = 0;
    int flag2 = n-1;
    for (int i = 0; i < n; i++)
    {
        if (oldLine[flag1]>oldLine[flag2])
        {
            newLine[i] = oldLine[flag2];
            flag2--;
        }
        else if (oldLine[flag1]<oldLine[flag2])
        {
            newLine[i] = oldLine[flag1];
            flag1++;
        }
        else
        {
            int s=equal(flag1, flag2);
            if (s==0)
            {
                newLine[i] = oldLine[flag2];
                flag2--;
            }
            else
            {
                newLine[i] = oldLine[flag1];
                flag1++;
            }
        }
    }

    for (int i = 0; i < n; i++)
    {
        cout << newLine[i];
        if ((i + 1) % 80 == 0)
        {
            cout << endl;//换行
        }
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/lanshan1111/article/details/84844070