22.Best Cow Line-最小的字符串

题目:

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.

输入:

<p>* Line 1: A single integer: <i>N</i><br>* Lines 2..<i>N</i>+1: Line <i>i</i>+1 contains a single initial ('A'..'Z') of the cow in the <i>i</i>th position in the original line</p>

输出:

<p>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.</p>

样例:

6
A
C
D
B
C
B

ABCBCD

题目大意:这边有个关于牛的比赛,每个农场主把他们的牛排成一条直线,将每个牛的首字母排列称为注册名,比如FJ带了Bessie,sylvia,dora这三个牛,则注册名为BSD,农场主参加比赛的顺序就是按照自己的注册名从小到大顺序,FJ很忙,所以要找出FJ带的牛中的最小的字符串顺序,排顺序时只能从队首和队尾找出牛排到注册名顺序中。

思路:从队首和队尾比较字符的大小,有大小之分就直接输出那个小的,队首队尾相同的话就继续找队首第二个和队尾第二个。

代码:

#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
    int n;
    char a[10010];
    cin>>n;
    for(int i=0; i<n; i++)
        cin>>a[i];
    int r=n-1,l=0,c=0,flage=0;   //r和l分别指向队尾和队首,flage为标志,
    while(l<=r)
    {
        for(int i=0; i<n; i++)   //这个循环里找出哪一边的是小的
        {
            if(a[l+i]<a[r-i])
            {
                flage=1;
                break;
            }
            if(a[l+i]>a[r-i])
            {
                flage=0;
                break;
            }
        }
        if(flage==0)
        {
            cout<<a[r];
            r--;
        }
        else
        {
            cout<<a[l];
            l++;
        }
        c++;
        if(c%80==0)
            cout<<endl;
    }
    return 0;
}



猜你喜欢

转载自blog.csdn.net/wentong_Xu/article/details/80668016