poj3617 Best Cow Line(贪心+字典序)

Best Cow Line
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 49343   Accepted: 12558

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

6
A
C
D
B
C
B

Sample Output

ABCBCD

题目大意:给定一个字符顺序,只能从这串字符的首端或末端取字符,通过一定的操作,使得到的字符串按字典序最小。
借鉴《挑战程序设计》一书的思路
依次比较首端和末端的字符的大小,将小的输出,若遇到相同的,则比较下一个位置的字母大小。
具体还是看细节实现。
代码如下:
 1 #include<iostream>
 2 #include<cstdio>
 3 using namespace std;
 4 const int maxn=2008;
 5 int main()
 6 {
 7     char a[maxn];
 8     int n;
 9     while(scanf("%d",&n)!=EOF)//多组输入
10     {
11     for(int i=1;i<=n;i++)
12     {
13         getchar();
14         scanf("%c",&a[i]);
15     }
16     int i=1,j=n;
17     int cnt=0;//统计已输出字符的数量
18     while(i<=j)
19     {
20         bool tag=false;
21         for(int k=0;i+k<=j;k++)//当两个字符相同时,便开始循环比较下一个字符
22         {
23             if(a[i+k]<a[j-k])
24             {
25                 tag=true;//判断标志
26                 break;
27             }
28             else if(a[i+k]>a[j-k])
29             {
30                 tag=false;//
31                 break;
32             }
33         }
34         if(tag)
35         {
36             printf("%c",a[i]);
37             i++;
38             cnt++;
39         }
40         else
41         {
42             printf("%c",a[j]);
43             j--;
44             cnt++;
45         }
46         if(cnt%80==0)//80个字符为一行
47             cout<<endl;
48     }
49     cout<<endl;
50     }
51     return 0;
52 }
原文地址:https://www.cnblogs.com/theshorekind/p/12573222.html