题意
输入两个字符串S和T。用S的子串和其子串的反转来凑T,要求尽可能的少使用子串数量。
思路
把S串的子串插入trie树中。dp[i]
表示T串的i到结尾最少要用到多少个S的子串。
dp[i]=min(dp[j]+1);
其中T的i到j-1的子串必须在trie树中。
路径还原。trie树中的每个节点都要记录该串的起点和终点。反串用负数记录较为方便。再用pr数组记录转移。
code
#include <bits/stdc++.h>
using namespace std;
#define MAXN 2100 + 5
char s[MAXN], t[MAXN];
int len_S, len_T;
int dp[MAXN];
int pr[MAXN];
pair<int, int> ans[MAXN];
struct trie_tree {
trie_tree* _ch[26];
int _l, _r;
trie_tree() {
for (int i=0; i<26; i++) _ch[i] = NULL;
}
};
void insert (trie_tree* root, char* s, int l) {
trie_tree* node = root;
char* p = s;
int r = l;
while (*p) {
if (node->_ch[*p - 'a'] == NULL) {
node->_ch[*p - 'a'] = new trie_tree();
}
node = node->_ch[*p - 'a'];
p++;
node->_l = l; node->_r = r;
r++;
}
}
int main () {
scanf ("%s %s", s, t);
int len_S = strlen(s);
int len_T = strlen(t);
trie_tree* root = new trie_tree();
for (int i=0; i<len_S; i++) {
insert(root, s+i, i+1);
}
reverse(s, s+len_S);
for (int i=0; i<len_S; i++) {
insert(root, s+i, i-len_S);
}
memset (dp, -1, sizeof(dp));
dp[len_T] = 0;
memset (pr, 0, sizeof(pr));
for (int i=len_T-1; i>=0; i--) {
char* p = t + i;
trie_tree* node = root, *tmp;
int mi = -1;
int _c = 0;
while (*p) {
_c ++;
if (node->_ch[*p - 'a'] == NULL) break;
if (dp[i + _c] != -1 && (mi == -1 || mi > dp[i + _c])) {
mi = dp[i + _c];
pr[i] = _c;
tmp = node->_ch[*p - 'a'];
ans[i] = make_pair(tmp->_l, tmp->_r);
}
node = node->_ch[*p - 'a'];
p++;
}
if (mi != -1) dp[i] = mi + 1;
}
printf ("%d\n", dp[0]);
int _c = 0;
while (pr[_c] != 0) {
printf ("%d %d\n", abs(ans[_c].first), abs(ans[_c].second));
_c = _c + pr[_c];
}
return 0;
}