码迷,mamicode.com
首页 > 其他好文 > 详细

uva 1548 Partitioning by Palindromes(动态规划)

时间:2014-11-28 21:26:20      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   on   

#include <iostream>
#include <string.h>
#include <string>
#define N 1002
using namespace std;

int f[N];
bool d[N][N];
/*
    如果(i,j)回文(i<=j),那么最小长度一定等于f[j+1]+1
    用动态规划解决回文串的判断节省时间,牺牲空间 
*/ 
int main()
{
//    freopen("D:/Documents/work/in.txt", "r", stdin);
    int n, t, i, j, result;
    cin>>t;
    while(t--)
    {
        string s;
        cin>>s;
        n=s.length();
        memset(f, 1000000, sizeof(f));
        memset(d, false, sizeof(d));
        for (int i = 0; i <= n; i++)
            f[i] = n-i;
        for (int i = n - 1; i >= 0; i--) {
            for (int j = i; j < n; j++) {
                if (s[i] == s[j] && (j-i<2 || d[i+1][j-1])) {
                    d[i][j] = true;
                    f[i] = min(f[i], f[j+1]+1);
                }
            }
        }
        cout<<f[0]<<endl;
    } 
    return 0;
}

uva 1548 Partitioning by Palindromes(动态规划)

标签:style   blog   io   ar   color   os   sp   for   on   

原文地址:http://www.cnblogs.com/vegg117/p/4129393.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!