本文主要是介绍POJ3617 Best Cow Line(字典序最小问题),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
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 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 Source USACO 2007 November Silver |
[Submit] [Go Back] [Status] [Discuss]
代码:
#include <stdio.h>
#include <string.h>
int main()
{int n;char a[2016];while(~scanf("%d",&n)){for(int i=0; i<n; i++)scanf("\n%c",&a[i]);//坑,字符在这里是一个一个输入的int a1=0,b1=n-1,p=0,l;while(a1<=b1)//当左边的小于右边的时候{l=0;for(int i=0; a1+i<=b1; i++)//利用这个处理等于的情况,如果碰到两个相等就去寻找下一个,判断输出左边的还是右边的{if(a[a1+i]<a[b1-i]){l=1;//输出左边的条件break;}else if(a[a1+i]>a[b1-i])break;//输出右边的条件}if(l)//判断l是否有值printf("%c",a[a1++]);elseprintf("%c",a[b1--]);if(++p == 80)//每到80头牛的时候,输出一个换行{putchar('\n');p = 0;}}printf("\n");}return 0;
}
PS:贪心的字典序最小问题。 字典序是指从前到后比较两个字符串大小的方法,首先比较第一个字符,如果不同则第1个字符较小的字符串更小,如果相同则继续比较第2个字符。。。。如此继续,比较整个字符串的大小
这篇关于POJ3617 Best Cow Line(字典序最小问题)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!