POJ-3617
Best Cow Line
Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 25616 Accepted: 6984 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 lineOutput
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 BSample Output
ABCBCD
题意:
对于与给出的字母,将它们按字典序最小的顺序排列输出。
采用 贪心的思想,每次取字典序最小的一个字母。
若首位字母相同,则向内收缩比较下一个,直到找出最小的。
AC代码:
1 //#include<bits/stdc++.h> 2 #include<iostream> 3 #include<stdio.h> 4 #include<String.h> 5 using namespace std; 6 7 int main(){ 8 ios::sync_with_stdio(false); 9 int n; 10 cin>>n; 11 char s[n+1]; 12 for(int i=0;i<n;i++){ 13 cin>>s[i]; 14 } 15 int a=0,b=n-1,ans=0; 16 while(a<=b){ 17 int flag=0; 18 for(int i=0;a+i<=b;i++){//若首位相等则比较下一个 19 if(s[a+i]<s[b-i]){ 20 flag=1; 21 break; 22 } 23 if(s[a+i]>s[b-i]){ 24 flag=0; 25 break; 26 } 27 } 28 if(flag){ 29 cout<<s[a++]; 30 ans++; 31 } 32 else{ 33 cout<<s[b--]; 34 ans++; 35 } 36 if(ans==80){ 37 ans=0; 38 cout<<endl; 39 } 40 } 41 cout<<endl; 42 return 0; 43 }