poj-3617-Best Cow Line

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a249900679/article/details/51183415

Best Cow Line
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 16833   Accepted: 4741

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


ps:题目是要我们把输入的字母按字典序排序,但是有要求,每次只能从左边取一个字母或右边取一个字母

可用贪心

思路:去左边第一个跟右边第二个比,取小的那个输出,如果一样则继续向下一个找

例如 输入ACDBCB

A<B,所以输出A,剩下CDBCB

B<C所以输出B,剩下CDBC

现在遇到一个问题了,两边都是C,该取哪个好呢?随便取一个?

答案当然不是,我们继续往前看,因为B<C,而D>C,得出了,我们应该选择右边的C,这样接下来就能选个更小的B,即剩下CDB

剩下的怎么选就不用我说了吧;


再来说说字典序排列:

指从左到右比较两个字符串大小的方法。

首先比较第一个字符,如果不同则第一个字符较小的字符串更小,如果相同则继续比较第二个字符。。。。以此类推,来比较整个字符串的大小。

例如:A=ABC, B=ABC,则A跟B一样大

A=ABCD, B=BAC,因为第一个字符A小于B,所以字符串A<B

A=ABCD, B=ABDC, 因为前两个字符一样,所以比较第三个,C<D,所以字符串A<B;


下面是AC代码:


#include<iostream>
#include<stdio.h>
#include<string.h>
#include<string>
#include<algorithm>
#include<queue>
#include<math.h>
using namespace std;

int main()
{
	int n;
	cin >> n;
	char a[2005];
	for (int i = 0; i < n; ++i)
	{
		cin >> a[i];
	}
	int left = 0, right = n - 1;
	while (left <= right)
	{
		for (int i = 0; left + i <= right; ++i)
		{
			if (a[left + i] < a[right - i])
			{
				cout << a[left++];
				break;
			}
			if (a[left + i] > a[right - i])
			{
				cout << a[right--];
				break;
			}
			if (left + i == right)
			{
				cout << a[left++];
				break;
			}
		}
		if ((left + n - right - 1) % 80 == 0)
		{
			cout << endl;
		}
	}
	cout << endl;

	return 0;
}







猜你喜欢

转载自blog.csdn.net/a249900679/article/details/51183415
今日推荐