Codeforces 750E New Year and Old Subsequence 线段树 + dp (看题解)

New Year and Old Subsequence

第一感觉是离线之后分治求dp, 但是感觉如果要把左边的dp值和右边的dp值合起来, 感觉很麻烦而且时间复杂度不怎么对。。

然后就gun取看题解了, 用线段树维护dp的值, 然后区间合并求答案。 每个节点保存dp[ i ][ j ]表示, 把当前管理的区间删到

s{2017}中的 s[ i + 1 ] - s[ j - 1 ],最少删几个, 然后合并的时候5 ^ 3合并。

#include<bits/stdc++.h>
#define LL long long
#define LD long double
#define ull unsigned long long
#define fi first
#define se second
#define mk make_pair
#define PLL pair<LL, LL>
#define PLI pair<LL, int>
#define PII pair<int, int>
#define SZ(x) ((int)x.size())
#define ALL(x) (x).begin(), (x).end()
#define fio ios::sync_with_stdio(false); cin.tie(0);

using namespace std;

const int N = 2e5 + 7;
const int inf = 0x3f3f3f3f;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + 7;
const double eps = 1e-8;
const double PI = acos(-1);

template<class T, class S> inline void add(T& a, S b) {a += b; if(a >= mod) a -= mod;}
template<class T, class S> inline void sub(T& a, S b) {a -= b; if(a < 0) a += mod;}
template<class T, class S> inline bool chkmax(T& a, S b) {return a < b ? a = b, true : false;}
template<class T, class S> inline bool chkmin(T& a, S b) {return a > b ? a = b, true : false;}


#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1
struct info {
    int a[5][5];
    info() {
        memset(a, inf, sizeof(a));
    }
    void go(char c) {
        for(int i = 0; i < 5; i++)
            for(int j = 0; j < 5; j++)
                a[i][j] = i == j ? 0 : inf;
        if(c == '2') a[0][0] = 1, a[0][1] = 0;
        else if(c == '0') a[1][1] = 1, a[1][2] = 0;
        else if(c == '1') a[2][2] = 1, a[2][3] = 0;
        else if(c == '7') a[3][3] = 1, a[3][4] = 0;
        else if(c == '6') a[3][3] = 1, a[4][4] = 1;
    }
};
info operator + (const info& x, const info& y) {
    info z;
    for(int i = 0; i < 5; i++)
        for(int j = i; j < 5; j++)
            for(int k = i; k < 5; k++)
                chkmin(z.a[i][j], x.a[i][k] + y.a[k][j]);
    return z;
}
info a[N << 2];
void build(char* s, int l, int r, int rt) {
    if(l == r) {
        a[rt].go(s[l]);
        return;
    }
    int mid = l + r >> 1;
    build(s, lson); build(s, rson);
    a[rt] = a[rt << 1] + a[rt << 1 | 1];
}
info query(int L, int R, int l, int r, int rt) {
    if(L <= l && r <= R) return a[rt];
    int mid = l + r >> 1;
    if(R <= mid) return query(L, R, lson);
    else if(L > mid) return query(L, R, rson);
    else return query(L, R, lson) + query(L, R, rson);
}

int n, q;
char s[N];

int main() {
    scanf("%d%d", &n, &q);
    scanf("%s", s + 1);
    build(s, 1, n, 1);
    while(q--) {
        int L, R;
        scanf("%d%d", &L, &R);
        info ans = query(L, R, 1, n, 1);
        printf("%d
", ans.a[0][4] == inf ? -1 : ans.a[0][4]);
    }
    return 0;
}

/*
*/
原文地址:https://www.cnblogs.com/CJLHY/p/10746369.html