您的位置:首页 > 其它

uva_11584_Partitioning by Palindromes( DP )

2013-05-06 20:30 429 查看
題意:

給你一個字符串,讓你去劃分該字符串,目標使得劃分出最小的回文串

分析:

一開始考慮是個區間DP,想都不想就寫了交上去,結果是TLE,後來發現數據量是10^3,區間DP的時間複雜度高達O(n^3),TLE是正常的

正解:

f[i]表示字符串底i個字符的時候,所能劃分的最小回文串的數量

f[i] = min(f[i], f[j]+cost(j+1,i)).

Code;

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

#define REPI(i, s, e)    for(int i = (s); i <= (e); i ++)
#define REPD(i, e, s)    for(int i = (e); i >= (s); i --)

const int MAXN = 1000;
const int INF  = 0x3f3f3f3f;

int f[MAXN+1];
char str[MAXN+1];

void input(void)
{
scanf("%s", str);
}

inline int ok(int l, int r)
{
int l_idx = l, r_idx = r;
while( l_idx <= r_idx ) {
if( str[l_idx] != str[r_idx] ) {
return 0;
}
l_idx += 1, r_idx -= 1;
}
return 1;
}

int process(void)
{
int len;

f[0] = 1;
len = strlen(str)-1;

for(int i = 1; i <= len; i ++) {
f[i] = INF;
for(int j = 0; j <= i; j ++) {
if( !ok(j, i) ) {
continue;
}
f[i] = min(f[i], ((!j)? 0 : f[j-1])+1);
}
}

return f[len];
}

int main(int argc, char **argv)
{
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
#endif
int cas;
scanf("%d", &cas);
REPI(k, 1, cas) {
input();
printf("%d\n", process());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: