best cow line(poj3617)

来源:互联网 发布:英国读研要求gpa算法 编辑:程序博客网 时间:2024/05/22 04:25

Best Cow Line

Description

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

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

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

FJ marks a location for a new line of the competingcows. He then proceeds to marshal the cows from the old line to the new one byrepeatedly 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 cowsfor registration in this new order.

Given the initial order of his cows, determine theleast 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') ofthe cow in theith 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') inthe new line.

Sample Input

6

A

C

D

B

C

B

Sample Output

ABCBCD

题意:

给定长度为N的字符串S,要构建一个长度为N的字符串T。起初,T是一个空串,随后又反复进行下列任意操作:

1.从S的头部删除一个字符,加到T的尾部。

2.从S的尾部删除一个字符,加到T的尾部。

目标是要构造字典序尽可能小字符串T。

思路:

利用贪心法,不断取S的开头和末尾中较小的一个字符放到T的末尾。如果S的开头和末尾相同,就比较下一个字符,如果还是相同,再循环,直到找到不同为止。如果开头的小,那么从开头取放到末尾,否则从末尾取放到末尾.

代码:

#include<cstdio>#include<iostream>using namespace std;int N;char s[2010];void init(){        scanf("%d",&N);        for(int i=0;i<N;i++)            cin>>s[i];}void solve(){    int a=0,b=N-1,count=0;    while(a<=b)    {        bool left=false;        for(int i=0;a+i<=b;i++)        {            if(s[a+i]<s[b-i])           {              left=true;              count++;            break;            }            else if(s[a+i]>s[b-i])         {             left=false;              count++;             break;         }        }if(left) putchar(s[a++]);else    putchar(s[b--]);if(count % 80 == 0)     cout<<endl;    } cout<<endl;}int main(){      init();     solve();    return 0;}


 

 

 

0 0
原创粉丝点击