1. 程式人生 > >簡單貪心演算法——字典序最小問題(Best Cow Line POJ3617)

簡單貪心演算法——字典序最小問題(Best Cow Line POJ3617)

題目連線

Best Cow Line POJ3617

題目描述

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.

Input

* Line 1: A single integer: N
* Lines 2..N+1: Line i+1 contains a single initial ('A'..'Z') of the cow in the ith position in the original line

Output

The least lexicographic string he can make. Every line (except perhaps the last one) contains the initials of 80 cows ('A'..'Z') in the new line.

Sample Input

6
A
C
D
B
C
B

Sample Output

ABCBCD

題目限制

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 33926 Accepted: 8929

思路

題目為簡單貪心思想,字典序問題可以聯想貪心演算法。從字串的左端和右端分別取其字元進行字典序比較,選其小的字元加入到T 的末尾。若其相同則分別從兩端向中間看下一位大小,直到找到可以區分大小的字元。如果全部相同,從左端還是右端取都可以。

程式碼

#include<iostream>
using namespace std;

const int MAX_N = 2000;
//輸入
int N ;
char S[MAX_N+1];
void solve()
{
    //剩餘的字串 s[a], s[a+1],s[a+2]...s[b]
    int  a = 0,b = N -1;
    int sum = 0;   //統計已經輸出的字元個數
    while(a <= b)
    {
        bool left = false;  //left標誌變數,標誌哪一端的字典序小
        for(int 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)
        {       
            cout<<S[a++];  
        }  
            
        else 
        {   
             cout<<S[b--]; 
            
        }

        sum++;
        if(sum % 80 == 0)
        {
            cout<<endl;
            sum = 0;
        }
           
    }
}

int main()
{
    cin>>N;
    for(int i=0;i < N;i++)
    {
         cin>>S[i];
    }
     solve();
    return 0;
}

總結

貪心目標為兩端最小的字元,字典序問題+貪心演算法