lightoj 1044 - Palindrome Partitioning(需要优化的区间dp)
生活随笔
收集整理的這篇文章主要介紹了
lightoj 1044 - Palindrome Partitioning(需要优化的区间dp)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目鏈接:http://lightoj.com/volume_showproblem.php?problem=1044
題意:求給出的字符串最少能分成多少串回文串。
一般會(huì)想到用區(qū)間dp暴力3個(gè)for但是這里的數(shù)據(jù)有1000,3個(gè)for肯定超時(shí)的。
但是這題只是判斷回文串有多少個(gè)所以可以先預(yù)處理一下[i,j]是不是回文,然后
就是簡(jiǎn)單dp了
for(int i = 1 ; i <= len ; i++) {
? ? ? ? ? ? ans[i] = ans[i - 1] + 1;
? ? ? ? ? ? for(int j = i - 1 ; j >= 1 ; j--) {
? ? ? ? ? ? ? ? if(dp[j][i]) {
? ? ? ? ? ? ? ? ? ? ans[i] = min(ans[i] , ans[j - 1] + 1);//如果[i,j]是回文那么就是ans[j-1]+1
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
#include <iostream> #include <cstring> #include <cstdio> using namespace std; int dp[1010][1010] , ans[1010]; char s[1010]; int main() {int t , cnt = 0;scanf("%d" , &t);while(t--) {cnt++;scanf("%s" , s + 1);int len = strlen(s + 1);memset(dp , 0 , sizeof(dp));memset(ans , 0 , sizeof(ans));for(int k = 0 ; k <= len ; k++) {for(int l = 1 ; l <= len && l + k <= len ; l++) {int r = l + k;if(s[l] == s[r]) {if(k == 0 || k == 1) {dp[l][r] = 1;}else {if(dp[l + 1][r - 1]) {dp[l][r] = 1;}}}else {dp[l][r] = 0;}}}for(int i = 1 ; i <= len ; i++) {ans[i] = ans[i - 1] + 1;for(int j = i - 1 ; j >= 1 ; j--) {if(dp[j][i]) {ans[i] = min(ans[i] , ans[j - 1] + 1);}}}printf("Case %d: %d\n" , cnt , ans[len]);}return 0; }轉(zhuǎn)載于:https://www.cnblogs.com/TnT2333333/p/6645796.html
總結(jié)
以上是生活随笔為你收集整理的lightoj 1044 - Palindrome Partitioning(需要优化的区间dp)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。