题解:CF1418G Three Occurrences

· · 题解

题目大意

给定一个数组 a,问这个数组中有多少段区间中所有出现的数都只出现了 3 次。

题目分析

常规思想,枚举右界然后看左界分别有多少种可能,假设枚举右界 R,则对于一个数 x,它最后出现的四次分别为 a_{x_1}, a_{x_2}, a_{x_3}, a_{x_4} 则左界只有可能在 (x_1, x_2] 或 (x_4, R] 之间,所以 L 即为所有数字上述条件的交集。

于是我们不妨记录一下每个点是否可以作为左界,动态维护,对于每个数,我们将处可行的区域外的点都赋上 1 否则为 0,则 L 可能的位置即为所赋值为 0 的部分。

于是问题就转化为了区间赋值,区间求 0 的个数,不难发现,赋完值后,每个点的值应都在 0 \sim n 之间,所以可以当成区间求最小值及最小值有几个,然后就是线段树板子了。

code

#include <iostream>
#include <cstdio>
#define mid ((l+r)>>1)
#define ls (p<<1)
#define rs (ls^1)
#define int long long

using namespace std;

const int N = 5e5 + 5;
int n, a[N], lst[N], mx[N], ans, tmn[N<<2], tsm[N<<2], tag[N<<2];

void push_up(int p)
{
    if(tmn[ls] == tmn[rs])
        tmn[p] = tmn[ls], tsm[p] = tsm[ls] + tsm[rs];
    else if(tmn[ls] < tmn[rs])
        tmn[p] = tmn[ls], tsm[p] = tsm[ls];
    else
        tmn[p] = tmn[rs], tsm[p] = tsm[rs];
}
void push_down(int p)
{
    if(tag[p] == 0) return ;
    tmn[ls] += tag[p], tag[ls] += tag[p];
    tmn[rs] += tag[p], tag[rs] += tag[p];
    tag[p] = 0;
}

void build(int p, int l, int r)
{
    if(l == r)
    {
        tmn[p] = 0, tsm[p] = 1, tag[p] = 0;
        return ;
    }
    build(ls, l, mid), build(rs, mid + 1, r);
    push_up(p);
}

void update(int p, int l, int r, int ll, int rr, int val)
{
    if(ll <= l && r <= rr)
    {
        tmn[p] += val, tag[p] += val;
        return ;
    }
    push_down(p);
    if(ll <= mid)   update(ls, l, mid, ll, rr, val);
    if(rr > mid)    update(rs, mid + 1, r, ll, rr, val);
    push_up(p);
}

int last(int x, int y){return !y || !x ? x : last(lst[x], y-1);}

signed main()
{
    scanf("%lld", &n);
    for(int i = 1;i <= n;i++)
    {
        scanf("%lld", &a[i]);
        lst[i] = mx[a[i]];
        mx[a[i]] = i;
    }
    build(1, 1, n);
    for(int i = 1;i <= n;i++)
    {
        if(last(i, 3) > last(i, 4))
            update(1, 1, n, last(i, 4) + 1, last(i, 3), 1);
        if(last(i, 2) > last(i, 3))
            update(1, 1, n, last(i, 3) + 1, last(i, 2), -1);
        if(last(i, 0) > last(i, 1))
            update(1, 1, n, last(i, 1) + 1, last(i, 0), 1);
        if(tmn[1] == 0)
            ans += (tsm[1] - (n-i));
        //printf("%lld\n", ans);
    }
    printf("%lld", ans);
    return 0;
}