POJ 3617 Best Cow Line - 贪心

来源:互联网 发布:软件股票最新上市公司 编辑:程序博客网 时间:2024/05/25 05:37

Best Cow Line
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 16160 Accepted: 4559

Description

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

6ACDBCB

Sample Output

ABCBCD

Source

USACO 2007 November Silver

看秋叶拓哉的白书时遇到的题目,参照书上的思路很容易做。这是一个求最小字典序字符串的问题,由于是每次把现有字符串头或尾的一个加到目标字符串的尾部,加得早的在目标串内更靠前,应该越小越好,很容易想到每次都加头尾中更小的那个。问题在于如果头尾一致,那么需要比较拿出后下一个的优劣,按照这个思路往里找,直到找到较小的就从那一端开始取(如果一直一样说明字符串是回文的,这一次从头或尾怎么拿都一样)。需要注意的是题目要求每输出80头牛换一行... N次Presentation Error后知道真相的我眼泪掉下来...还是太小白了

#include <iostream>#include <cstdio>using namespace std;int N;char cows[2010];int main(){scanf("%d",&N);for (int i = 0; i < N; i++)cin >> cows[i];int start = 0, end = N - 1, count = 0;while (start <= end){bool left = false;for (int i = 0; start+i<=end; i++){if (cows[start + i] < cows[end - i]){left = true;break;}else if (cows[start + i]>cows[end - i]){left = false;break;}}if (left) putchar(cows[start++]);else putchar(cows[end--]);count++;if (count % 80 == 0) putchar('\n');}putchar('\n');return 0;}




0 0
原创粉丝点击