演算法:uva 1351 String Compression(字串區間dp)

來源:互聯網
上載者:User

題目大意

給一個字串,可以把連續相同的部分進行縮寫成k(S)的形式,S是一個字串,k表示 有連續相同的S

例如,abgogogogo,可以縮寫成ab4(go). 還可以嵌套縮寫,比如

“nowletsgogogoletsgogogo”, 縮寫成“now2(lets3(go))”

思路

一道區間dp,但是這題並 不好想

f(i, j)表示字串的i~j位的最小位元

那麼

f(i, j) = min{

 min{ f(i,k)+f(k+1, j), i<=k<j },

 min{ digitNum(k)+f[l][l+k-1]+2, 如果字串可以由前k個字串重複的群組 成的 }

}

digitNum(k)表示數字k的位元

判斷區間(i, j)是否有由連續k個組成的字串連續 組成的,直接用O(n)的時間判斷

代碼

/**==========================================* This is a solution for ACM/ICPC problem** @source:uva-1351 String Compression* @type: 區間dp* @author: shuangde* @blog: blog.csdn.net/shuangde800* @email: zengshuangde@gmail.com*===========================================*/#include<iostream>#include<cstdio>#include<algorithm>#include<vector>#include<queue>#include<cmath>#include<cstring>using namespace std;    typedef long long int64;const int INF = 0x3f3f3f3f;const double PI = acos(-1.0);    const int MAXN = 210;char str[MAXN];int f[MAXN][MAXN], len;        // 判斷字串區間[l,r]之否由[l,l+k-1]字串聯續組成的bool check(int l, int r, int k){int len = r-l+1;int i = 0;while(i < k){for(int p=1; l+p*k+i<=r; ++p){if(str[l+i] != str[l+p*k+i])return false;}++i;}return true;}    // 計算數字x有幾位// http://www.bianceng.cninline int digitNum(int x){int cnt = 0;while(x > 0){ ++cnt; x /= 10; }return cnt;}    int main(){    int nCase;scanf("%d", &nCase);    while(nCase--){scanf("%s", str+1);len = strlen(str+1);    for(int i = 1; i <= len; ++i)f[i][i] = 1;    for(int d = 2; d <= len; ++d) {for(int l = 1; l+d-1 <= len; ++l) {    int r = l + d - 1;    f[l][r] = INF;int& ret = f[l][r];    for(int k=l; k<r; ++k)ret = min(ret, f[l][k]+f[k+1][r]);    for(int k = 1; k <= d/2; ++k) {if(d%k!=0) continue;if(check(l, r, k)){ret = min(ret, digitNum(d/k) + f[l][l+k-1] + 2);}}}}printf("%d\n", f[1][len]);}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.