codeforces 615 C. Running Track trie + dp

题意

输入两个字符串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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值