POJ3617 字符串问题

Best Cow Line
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 15444   Accepted: 4363

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


遇到的问题和解题思路:

        刚开始看到这道题是在书上,当时的时候看到这道题感觉需要在重新创建一个数组,然而发现书上并没有这么做,而是很巧妙地就输出了最小数组(挑战p44)。然而书上的例题和实际上的题目改动了挺多的。书上就是大致将题目意思表示出来,然而题目还有故事背景,还有一个字符串输出的时候大于80个要换行(这一点由于直接看书上就做了,然后一直PE,TAT直到看到了别人的代码才恍然大悟,下次应该多留心)。

       我的思路就是通过比较,将所有的字母放到另外一个数组里面去,然后输出就可以了。


给出代码:


#include
#include
#include
#include

using namespace std;

char ch[2005],co[2005];
int n;
bool flag;

void solve(){
	int left = 0,right = n - 1;
	int res = 0;
	while(left <= right){
		flag = false;
		for(int i = 0;i + left <= right ;i++){//i + left <= right保证左右移动 
			if(ch[left + i] > ch[right - i]){
				flag == false;//为了更清楚的能理解,就写一下 
				break;
			}
			else if(ch[left + i] < ch[right - i]){
				flag = true;
				break;
			}
		}
		
		if(flag){
			co[res] = ch[left++];
			res++;
		}
		else {
			co[res] = ch[right--];
			res++;
		}
		co[res] = '\0';
	}
	//printf("%d\n",strlen(co));
	for(int i = 0;co[i] != '\0';i++){
		if(i % 80 == 0 && i!=0)printf("\n");
     	printf("%c",co[i]);	
		
	}

	printf("\n");
}

int main(){
	while(scanf("%d",&n)!=EOF){
		memset(ch,'\0',sizeof(ch));
		memset(co,'\0',sizeof(co));
		getchar();
		for(int i = 0; i < n;i++){
			scanf("%c",&ch[i]);
			getchar();
		}
		solve();
	}
	return 0;
} 


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