NYOJ 37 迴文字串

來源:互聯網
上載者:User

標籤:style   blog   http   color   strong   os   

迴文字串時間限制:3000 ms  |  記憶體限制:65535 KB難度:4 
描述
所謂迴文字串,就是一個字串,從左至右讀和從右至左讀是完全一樣的,比如"aba"。當然,我們給你的問題不會再簡單到判斷一個字串是不是迴文字串。現在要求你,給你一個字串,可在任意位置添加字元,最少再添加幾個字元,可以使這個字串成為迴文字串。
 
輸入
第一行給出整數N(0<N<100)
接下來的N行,每行一個字串,每個字串長度不超過1000.
輸出
每行輸出所需添加的最少字元數
範例輸入
1Ab3bd
範例輸出
2
來源
IOI 2000
上傳者
hzyqazasdf


解題:很狠狠狠經典的dp題目啊。。。。叫什麼來著?最長公用子序列。。。。。長度-最長公用子序列就是我們要的結果啊。。。。

 1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <vector> 6 #include <climits> 7 #include <algorithm> 8 #include <cmath> 9 #define LL long long10 using namespace std;11 char a[1100],b[1100];12 int dp[2][1100];13 int main(){14     int ks,i,len,j;15     scanf("%d",&ks);16     while(ks--){17         scanf("%s",a);18         len = strlen(a);19         for(i = 0; i < len; i++)20             b[len-i-1] = a[i];21         b[len] = ‘\0‘;22         memset(dp,0,sizeof(dp));23         for(i = 1; i <= len; i++){24             for(j = 1; j <= len; j++){25                 if(a[i-1] == b[j-1]){26                     dp[i%2][j] = dp[(i-1)%2][j-1]+1;27                 }else dp[i%2][j] = max(dp[(i-1)%2][j],dp[i%2][j-1]);28             }29         }30         printf("%d\n",len-dp[(i-1)%2][j-1]);31     }32     return 0;33 }
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.