POJ3617 簡單字串

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   for   ar   

  三分之一的通過率的字串

 

  題意為,輸入一個S串,有一個空串T。對S串有兩種操作,一是取出S串的頭放入T串的尾,二是取出S串的尾放入T串的尾。要求是要使得T串的字典序最小。

 

  從題意來看是一個很明顯的貪心思路。那麼想到這一步其實比較接近答案了,但是需要注意的一點是當S串的頭和尾相同的時候,那麼這個時候我們當然也希望取出更小的字元,所以就需要比較下一個字元。但是如果指向頭和尾的指標都分別往裡前進一位的時候,這倆字元還是相同,咋辦?這個情形。。。對,就是迴文字串。形同“ABCDCBA”這樣的字串。這個時候是指標不斷地往裡走,判斷為迴文字串的時候,兩頭任意取下一個即可。還有一種情形是類似於這樣的串:“ABCCBA”以及“ABCABA”。這些都需要我們把指標不斷地移動到中間的時候才能夠判斷出應該先取哪邊的字串才能保證T串的字典序最小。

  

 1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 #include <algorithm> 5 using namespace std; 6 const int maxn = 2000+10; 7 char s[maxn]; 8  9 void solve(int n)10 {11     int i,l,r,cnt;12     l = 0;13     r = n-1;14     for(cnt=1; l<=r; cnt++)15     {16         bool left = false;17         for(i=0; l+i<=r; i++)18         {19             if(s[l+i] < s[r-i])20             {21                 left = true;22                 break;23             }24             else if(s[l+i] > s[r-i])25             {26                 left = false;27                 break;28             }29             if((l+i == r-i) && s[l+i] == s[r-i])30             {31                 left = true;32                 break;33             }34             if((l+i+1 == r-i) && s[l+i] == s[r-i])35             {36                 left = true;37                 break;38             }39         }40         //if(top == n-1) left = true;41         if(left) putchar(s[l++]);42         else putchar(s[r--]);43         if(n % 80 != 0)44             if(cnt % 80 == 0)45                 printf("\n");46     }47 }48 49 int main()50 {51     int n,i;52     while(scanf("%d%*c",&n) == 1)53     {54         char x;55         memset(s,0,sizeof(s));56         for(i=0; i<n; i++)57         {58             scanf("%c%*c",&x);59             s[i] = x;60         }61         s[i] = ‘\0‘;62         solve(n);63     }64     return 0;65 }
View Code

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.