題目連接:http://poj.org/problem?id=3617數組
Descriptionapp
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.ide
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.this
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.spa
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.code
Given the initial order of his cows, determine the least lexicographic string of initials he can make this way.blog
Inputip
* 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 lineci
Outputrem
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串。
從S的頭部刪除一個字符,加到T的尾部
從S的尾部刪除一個字符,加到T的尾部
目標是構造字典序儘量小的字符串。
解題思路:剛開始看到這題就想用兩個字符數組,經過比較S的開頭和末尾的大小中較小的放入T的末尾,當兩個相等的時候就沒細想,就隨便選一個,而後碼完發現連樣例都經過不了,發現本身仍是太差了,那麼關鍵的狀況居然沒有細想。這裏咱們採用貪心的思想,若是末尾和開頭相同,咱們則要比較下一個字符的大小,下一個字符也有可能相同
附上代碼:
1 #include<stdio.h> 2 #include<string.h> 3 int s[2005]; 4 int main() 5 { 6 int n; 7 while(scanf("%d",&n)!=EOF) 8 { 9 getchar(); 10 for(int i=0;i<n;i++) 11 { 12 scanf("%c",&s[i]); 13 getchar(); 14 } 15 int a=0,b=n-1; 16 int ans=0; 17 while(a<=b) 18 { 19 bool left=false; 20 for(int i=0;a+i<=b;i++) 21 { 22 if(s[a+i]>s[b-i]) 23 { 24 left=false; 25 break; 26 } 27 else if(s[a+i]<s[b-i]) 28 { 29 left=true; 30 break; 31 } 32 } 33 if(left) 34 { 35 putchar(s[a]); 36 a++; 37 } 38 else 39 { 40 putchar(s[b]); 41 b--; 42 } 43 ans++; 44 if(ans==80) 45 { 46 printf("\n"); 47 ans=0; 48 } 49 } 50 printf("\n"); 51 } 52 return 0; 53 }