首页 > 代码库 > poj 3617 Best Cow Line (字符串反转贪心算法)
poj 3617 Best Cow Line (字符串反转贪心算法)
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 9284 | Accepted: 2826 |
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
6ACDBCB
Sample Output
ABCBCD
AC代码:
1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 #include<cstring> 5 #include<string> 6 #include<cmath> 7 #include<map> 8 #include<queue> 9 using namespace std;10 char s[2010],s1[2010];11 int compare(int x,int y,int t)12 {13 //cout<<x<<"**"<<y<<endl;14 //cout<<"*"<<s[1]<<"*"<<endl;15 // cout<<s[x]<<"^^"<<s1[y]<<endl;16 int j=0;17 while(j<=t)18 {19 20 if(s[x]<s1[y])21 return 1;22 else if(s[x]>s1[y])23 return 2;24 x++;y++;j++;25 }26 return 0;27 }28 int main()29 {30 int i,j,k,t,m,n;31 while(cin>>t)32 {33 for(int i=0,j=t-1;i<t;i++,j--)34 {35 cin>>s[i];36 s1[j]=s[i];37 }38 n=t;39 int x=0,y=0,ans=0;40 while(n--)41 {42 int kk=compare(x,y,n);43 if(kk==1 || kk==0)44 {45 cout<<s[x];46 x=x+1;47 }48 else if(kk==2)49 {50 cout<<s1[y];51 y=y+1;52 }53 ans++;54 if(ans%80==0)55 cout<<endl;56 }57 }58 return 0;59 }