POJ 3617 — 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 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

题目链接

http://poj.org/problem?id=3617

题目翻译

给定长度为n 的字符串S,现要构造一个长度为n 的字符串T. 初始T 为空串,随后的每一步操作,可以从S头部删除一个字符加到T 的尾部,或是从S 尾部删除一个字符加到T的尾部,直到S为空,求字典序最小的T
(1 ≤ N ≤ 2000)

输出

每80个字符换行一次。

题目分析

对于每一次操作,可以选择S头部的字符或者S尾部的字符,只要选择其中字典序较小的就行了。如果这两个字符相等,那么比较这两个字符的下一个字符,直到找到不相同的那两个字符;如果找不到,那么选择头部还是尾部是相同的,随便选一个就行。

AC代码

#include <iostream>
using namespace std;

int main()
{
    int i, j, n, index;
    char s[2005], t[2005];
    cin >> n;
    for (i = 0; i < n; i++)
        cin >> s[i];
    i = 0, j = n - 1, index = 0;
    while (i <= j)
    {
        int i2 = i, j2 = j;
        while (i2 <= j2) //判断应该选择左边还是右边
        {
            if (s[i2] > s[j2])
            {
                t[index] = s[j];
                j--;
                break;
            }
            else if (s[i2] < s[j2])
            {
                t[index] = s[i];
                i++;
                break;
            }
            else //当前的字符相等,比较下一个字符
            {
                i2++;
                j2--;
            }
        }
        if (i2 > j2) //选择左边和右边都完全相同
        {
            t[index] = s[j];
            j--;
        }
        index++;
    }
    for (i = 0; i < n; i++)
    {
        cout << t[i];
        if ((i + 1) % 80 == 0)
            cout << endl;
    }
    return 0;
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部