forked from sureshmangs/Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpalindromic_partitioning_memoization.cpp
139 lines (99 loc) · 2.82 KB
/
palindromic_partitioning_memoization.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
/*
Given a string, a partitioning of the string is a palindrome partitioning if every
sub-string of the partition is a palindrome. For example, “aba|b|bbabb|a|b|aba”
is a palindrome partitioning of “ababbbabbababa”. Determine the fewest cuts
needed for palindrome partitioning of a given string. For example, minimum 3
cuts are needed for “ababbbabbababa”. The three cuts are “a|babbbab|b|ababa”.
Input:
The first line of input contains an integer T, denoting the number of test cases.
Then T test cases follow. The first line of every Test Case consists of S, denoting a String.
Output:
For each test case in a new line print an integer,
denoting the number cuts in the String to make it palindromic.
Constraints:
1<=T<=100
1<=|Length of String|<=1000
Example:
Input:
2
ababbbabbababa
aaabba
Output:
3
1
*/
// Accepted on LC
class Solution {
public:
vector<vector<int>> dp;
bool isPalindrome(int start, int end, string &s) {
while (start < end) {
if (s[start++] != s[end--]) return false;
}
return true;
}
int solve (int i, int j, string &s){
if(i>=j || isPalindrome(i, j, s)) return 0;
if(dp[i][j]!=-1) return dp[i][j];
int res = INT_MAX;
for (int k = i; k < j; k++){
if (isPalindrome(i, k, s)){
int tmp = solve (k + 1, j, s) + 1;
res = min (res, tmp);
}
}
return dp[i][j] = res;
}
int minCut(string s) {
int n = s.length();
dp.resize(n, vector<int> (n, -1));
return solve (0, n - 1, s);
}
};
#include<bits/stdc++.h>
using namespace std;
int dp[1001][1001];
bool isPalindrome(string s, int i, int j){
if(i==j) return true;
if(i>j) return true;
while(i<j){
if(s[i]!=s[j]) return false;
i++; j--;
}
return true;
}
int palindromicPartion(string s, int i, int j){
if(i>=j) return 0;
if(isPalindrome(s, i, j)) return 0;
if(dp[i][j]!=-1) return dp[i][j];
int partition=INT_MAX;
int left, right;
for(int k=i;k<j;k++){
if(dp[i][k]!=-1) left=dp[i][k];
else { left=palindromicPartion(s, i, k);
dp[i][k]=left;
}
if(dp[k+1][j]!=-1) right=dp[k+1][j];
else { right=palindromicPartion(s, k+1, j);
dp[k+1][j]=right;
}
int tmp = 1 + left + right;
if(tmp<partition) partition=tmp;
}
return dp[i][j]=partition;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t;
cin>>t;
while(t--){
string s;
cin>>s;
int n=s.length();
memset(dp, -1, sizeof(dp));
cout<<palindromicPartion(s,0,n-1)<<endl;
}
return 0;
}