回文分割
このアルゴリズムでは、入力は文字列であり、パーティションのすべてのサブストリングが回文である場合、その文字列のパーティション化は回文パーティション化です。
このアルゴリズムでは、指定された文字列をパリンドロームで分割するために必要な最小限のカットを見つける必要があります。
入力と出力
Input: A string. Say “ababbbabbababa” Output: Minimum cut to partition as palindrome. Here 3 cuts are needed. The palindromes are: a | babbbab | b | ababa
アルゴリズム
minPalPart(str)
入力: 指定された文字列。
出力: 文字列からの回文分割の最小数。
Begin n := length of str define cut matrix and pal matrix each of order n x n for i := 0 to n, do pal[i, i] := true cut[i, i] := 0 done for len in range 2 to n, do for i in range 0 to n – len, do j := i + len – 1 if len = 2, then if str[i] = str[j] pal[i, j] := true else if str[i] = str[j] and pal[i+1, j-1] ≠ 0 pal[i, j] := true if pal[i, j] is true, then cut[i, j] := 0 else cut[i, j] := ∞ for k in range i to j-1, do cut[i, j] := minimum of cut[i, j] and (cut[i, k]+ cut[k+1, j+1]+1) done done done return cut[0, n-1] End
例
#include <iostream>
using namespace std;
int min (int a, int b) {
return (a < b)? a : b;
}
int minPalPartion(string str) {
int n = str.size();
int cut[n][n];
bool pal[n][n]; //true when palindrome present for i to jth element
for (int i=0; i<n; i++) {
pal[i][i] = true; //substring of length 1 is plaindrome
cut[i][i] = 0;
}
for (int len=2; len<=n; len++) {
for (int i=0; i<n-len+1; i++) { //find all substrings of length len
int j = i+len-1; // Set ending index
if (len == 2) //for two character string
pal[i][j] = (str[i] == str[j]);
else //for string of more than two characters
pal[i][j] = (str[i] == str[j]) && pal[i+1][j-1];
if (pal[i][j] == true)
cut[i][j] = 0;
else {
cut[i][j] = INT_MAX; //initially set as infinity
for (int k=i; k<=j-1; k++)
cut[i][j] = min(cut[i][j], cut[i][k] + cut[k+1][j]+1);
}
}
}
return cut[0][n-1];
}
int main() {
string str= "ababbbabbababa";
cout << "Min cuts for Palindrome Partitioning is:" << minPalPartion(str);
} 出力
Min cuts for Palindrome Partitioning is: 3
-
ロッドカッティング
ロッドの長さはnです。別の表も用意されており、サイズごとに異なるサイズと価格が含まれています。ロッドをカットして市場で販売することにより、最高価格を決定します。 さまざまな位置でカットし、ロッドをカットした後の価格を比較することで、最良の価格を得るには。 長さnの行を切り取った後、f(n)が可能な最大価格を返すようにします。このように関数f(n)を書くだけです。 f(n):=price [i] + f(n – i – 1)の最大値。ここで、iは0から(n – 1)の範囲です。 入力と出力 入力 : さまざまな長さの価格、およびロッドの長さ。ここでの長さは8です。 出力 :
-
アレイが回文であるかどうかをチェックするCプログラム
任意のサイズnの配列arr[]が与えられた場合、私たちのタスクは、配列が回文であるかどうかを確認することです。回文は、MADAM、NAMANなどのように、同じように前後に読み取ることができるシーケンスです。 したがって、配列が回文であるかどうかを確認するために、-のように配列を前後にトラバースできます。 例 Input: arr[] = {1, 0, 0, 1} Output: Array is palindrome Input: arr[] = {1, 2, 3, 4, 5} Output: Array is not palindrome 以下で使用されるアプローチは次のとおりです