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

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

题目大意:

给定长度为N的字符串S,要构造一个长度为N的字符串T,刚开始T为空串。每一次只能从S的头部和尾部选择一个较小的字符放在T尾部,目标是构造字典序尽可能小的字符串。

解题思路:贪心策略,定义两个变量分别指向S的头部和尾部,如果s[left]>S[right],就将S[right]放在T的尾部,如果S[left]<S[right]就将S[right]放在T的尾部,如果S[left]==S[right],就继续比较下一位,直到选择出较小的那一个。然后根据当前这个较小的一个在左边还是右边选择将S[left]后者S[right]放在T尾部

AC代码:

#include<iostream>
using namespace std;
const int maxn=1e4;
char str[maxn];
int main()
{
	int n;
	char c;
	cin>>n;
	for(int i=0;i<n;i++)
	{
		cin>>str[i];
	}
	int left=0,right=n-1;
	int flag=0,cnt=0;
	while(left<=right)
	{
		if(str[left]>str[right])
		{
			cout<<str[right];
			right--;
			cnt++;
		}
		else if(str[left]<str[right])
		{
			cout<<str[left];
			left++;
			cnt++;
		}
		else//相等 
		{
			int i=left,j=right;
			while(i<=j)
			{
				if(str[i]==str[j])
				{
					i++;
					j--;
				}
				else if(str[i]>str[j])
				{
					cout<<str[right];
					cnt++;
					right--;
					break;
				}
				else
				{
					cout<<str[left];
					left++;
					cnt++;
					break;
				}
			}
			if(i>j)
			{
				cout<<str[left];
				cnt++;
				left++;
			}
		}
		if(cnt%80==0)
		cout<<endl;
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_40707370/article/details/86611147