本文主要是介绍lightoj 1044 Palindrome Partitioning(dp),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题意:给定字符串S,问可以划分的最小回文串数量
思路:定义dp[i]为以i开头的字符串中回文串的最小划分数.
dp[i] = min(dp[j] + 1 | i <= j < n && S[i...j]是回文串)
边界,dp[i] = n-i+1.
/************************************************ Author: fisty* Created Time: 2015-08-22 09:25:11* File Name : 1044.cpp*********************************************** */
#include <iostream>
#include <cstring>
#include <deque>
#include <cmath>
#include <queue>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <string>
#include <vector>
#include <cstdio>
#include <bitset>
#include <algorithm>
using namespace std;
#define Debug(x) cout << #x << " " << x <<endl
#define Memset(x, a) memset(x, a, sizeof(x))
const int INF = 0x3f3f3f3f;
typedef long long LL;
typedef pair<int, int> P;
#define FOR(i, a, b) for(int i = a;i < b; i++)
#define lson l, m, k<<1
#define rson m+1, r, k<<1|1
#define MAX_N 1010
int t, n;
string s;
int is_palindrome[MAX_N][MAX_N];
int dp[MAX_N];
bool is_ok(int i, int j){while(i < j){if(s[i++] != s[j--])return false;}return true;
}
void init(){Memset(is_palindrome, 0);for(int i = 0;i < n; i++){for(int j = i;j < n; j++){if(is_ok(i, j)){is_palindrome[i][j] = 1;}}}
}
void solve(){Memset(dp, -1);for(int i = n-1;i >= 0; i--){if(dp[i] != -1) break;if(is_palindrome[i][n-1]) {dp[i] = 1; continue;}dp[i] = n-i+1;for(int j = i;j < n-1; j++){if(is_palindrome[i][j]){dp[i] = min(dp[i], dp[j+1]+1);// Debug(dp[i]);}}}printf("%d\n", dp[0]);
}
int main() {//freopen("in.cpp", "r", stdin);//cin.tie(0);//ios::sync_with_stdio(false);scanf("%d", &t);int cnt = 1;while(t--){cin >> s;n = s.length();init();printf("Case %d: ", cnt++);solve();}return 0;
}
这篇关于lightoj 1044 Palindrome Partitioning(dp)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!