uva 11584 - Partitioning by Palindromes(簡單dp)
阿新 • • 發佈:2018-12-13
https://vjudge.net/problem/UVA-11584
題目大意:
給一個字串, 要求把它分割成若干個子串,使得每個子串都是迴文串。問最少可以分割成多少個。
簡單dp,P276.
#include<cstdio> #include<algorithm> #include<ctime> #include<iostream> #include<cmath> #include<string.h> using namespace std; #define N 1000 char s[N]; // 檢查是否為迴文串 bool isPalindrome(int l,int r) { while(l < r){ if(s[l] != s[r]) return false; ++l; --r; } return true; } int main() { bool isPalindrome(int l,int r); int t,n,imin; int dp[N]; scanf("%d",&t); while(t--) { scanf("%s",s); n=strlen(s); if(n<=1) { cout<<n<<endl; continue; } dp[0]=0; dp[1]=1; for(int i=2;i<=n;i++) { dp[i]=dp[i-1]+1; for(int j=0;j<i;j++) if(isPalindrome(j,i-1)) { dp[i]=min(dp[j]+1,dp[i]); } } cout<<dp[n]<<endl; } }
需要說明的問題:
1. 本題目和https://blog.csdn.net/qiang_____0712/article/details/84679892相同,但是需要輸出所以的,得用回溯法。
本題目需要輸出最小次數,使用dp。
2.該題目的複雜度為n^3,也有複雜度為n^2,的,參見