poj 3617

Best Cow Line
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 14849   Accepted: 4219

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

如果F.J想尽可能早点参加比赛的话,就要找出一个字典序最小的序列,才能尽早的轮到他。所以本道题需要从给定的顺序中找到一个字典序升序中的最小字典序,从头部和尾部选择字母。需要比较尾部和头部,把较小的那一个读出来,然后再次比较,把较小的选择出来。如果相等,然后比较头部的下一个跟尾部的前一个数据中的最小值。就这样,就能构造出一个字典序最小的序列。还要注意,因为是80头牛一列,所以每80个字母要换一次行。还要注意,这是多组数据,并不是只有一组。

源代码:

#include <cstdio>
char s[2003];
int n;
void solve();
int main()
{
 int i;
 char k;
 while (~scanf("%d", &n))
 {
  getchar();
  for (i = 0; i < n; i++)
  {
   scanf("%c",&k);
   s[i] = k;
   getchar();
  }
  s[n] = '\0';
  solve();
 }
}
void solve()
{
 int begin = 0;
 int end = n - 1;
 int cnt = 0;
 while (begin <= end)
 {
  bool left = false;
  int i = 0;
  for(;begin+i<=end;i++)
  {
   if(s[begin+i]<s[end-i])
   {
    left =true;
    break;
   }
   else if(s[begin+i]>s[end-i])
   {
    break;
   }
  }
  if (left)
   putchar(s[begin++]);
  else
   putchar(s[end--]);
  cnt++;
  if(cnt%80==0)
  {
   putchar('\n');
  }
 }
}

你可能感兴趣的:(poj,贪心算法)