P4690 [Ynoi2016] 镜中的昆虫 题解

题目链接:镜中的昆虫

经典题了,我们首先回顾下颜色数的常见做法统计:

对每个位置维护一个 \(pre_i\),表示与当前位置相同的颜色上一次出现位置。那么我们分讨一下。

查询 \([l,r]\) 得到颜色数,对于 \(pre_i<l\)\(i\) 点,显然它就是这个区间内 \(a_i\) 对应颜色出现的第一个位置,我们把它作为贡献点,而其他的 \(pre_i \ge l\),显然意味着,在当前区间内是存在前驱贡献点的,并不需要作为贡献点。所以颜色问题就转化为询问 \(i \in [l,r]\) 上有多少个 \(pre_i<l\)

本题涉及到了区间覆盖,那么很显然,对于单纯地暴力修改每个 \(pre\) 是不现实的,这里先考虑不带修的区间段问题。

如果有若干段连续颜色段,询问某个段的颜色个数,那么一个考虑不带修,区别于传统的 \(HH的项链\) 问题解决方式,我们是预处理以后跑扫描线去做的,本质也是二维数点:我的某篇讲解文。参照了下题解区的一些大佬和我之前写的这篇文章,我对颜色数又有了新的看法。

对于一个极长连续颜色段,我们可以沿用之前文章中提到的代表元和作用范围的观点,对于一个极长颜色段来说,我们的当前点的作用范围为 \([pre[i],i]\),代表元为 \(color_{first}\)。为什么选第一个点作为代表元贡献,那是因为,对于一个颜色段来说,它的贡献只有 \(1\),而这个贡献可以选自这里面的任意一个元素,我们强制规定第一个点元素进行贡献,方便处理。

我们现在加上带修,看看上面的观点是否正确。对于如果上述的极长颜色连续段 \([l,r]\) 遇上了带修区间 \([L,R]\) 考虑有部分交集,并且二者颜色不同:

  1. \(l<L,R\le r\),这个时候会分为两段,显然前段 \([l,L-1]\) 依旧还是第一个颜色作为代表元,后半段则为 \([L,r]\)\(L\) 作为新一段的代表元,显然是非常容易做到的。

  2. \(1\) 的基础上,\(R<r\),那么就是分为三段,最后两段为 \([L,R]\),最后一段 \([R+1,r]\),显然这三个极长连续段的第一个元素都可以分别作为代表元元素,且非常容易操作。

那么其实关于极长连续段我们就可以抽象为 \((pre[i],i)\) 的贡献,其中 \(i\) 为这个连续段的第一个元素,类似化段为点的思想,不得不说颜色数这个真是经典又永无止境的问题。

那么考虑正儿八经的带修,这玩意在线显然树套树空间好像不是很行,毕竟 \(64mb\) 限制,那么显然考虑离线,离线带修又有二维数点的,那么显然是 \(cdq分治\) 了。

现在考虑构造出修改与查询,查询很简单,对于区间查询,并且颜色数这个问题属于可差性问题,可以转化为前缀和作差:\([0,r]\) 上的颜色数减去 \([0,l-1]\) 上的颜色数。

考虑如何快速修改上述提到的极长连续颜色段,一个比较自然的想法就是分桶,为每个颜色进行分桶,那么我们可以快速知道待修改的颜色段。为了快速定位到 \([l,r]\) 的插入与删除,我们使用平衡树维护每个颜色桶。对于修改 \(pre\) 和传统颜色数问题一样,先去掉原有的 \(pre\) 贡献,再加入新的 \(pre\) 贡献。

  1. 对于某个颜色桶中增加一个 \([l,r]\),我们可以快速基于二分出红色段,考虑 \(last\) 段的开头 \(l\) 修改 \(pre\)\(l\)。而 \(l\) 处的 \(pre\) 应该修改该为蓝色段 \(pre\)\(l\)

  2. 对于删除,显然只需要考虑 \(last\)\(pre\) 变为了蓝色段的 \(l\)

当然蓝色段不存在的情况下自然是 \(0\) 了,特判一下。

对于一个 \([l,r]\) 上如何知道需要删除以及增加哪种颜色的连续段,这个玩意 \(ODT\) 就能办到,本题由于 \(ODT\) 只与修改的查询有关,修改只有区间赋值,所以复杂度也是完全正确的。非随机数据下的 \(ODT\) 这种颜色均摊为 \(O(n)\),即最坏的时候就是 \([l,l]\) 的修改。

这里简单提提什么情况下 \(ODT\) 在非随机数据向下会被卡,首先除了区间覆盖操作以外,还有其他的操作,比如区间加操作,那么构造卡的数据很简单,比如区间 \(+\),在初始状态下反复 \([1,n]\) 进行 \(+\),每次修改即为 \(O(n)\)。另一种拥有区间查询询问,由于数据不随机,我们的 \([l,r]\) 可以每次 \([l,l]\) 使得颜色段数无法均摊到 \(\log{n}\),这个时候查询每次 \([1,n]\),那么查询的单次复杂度即为 \(O(n)\),也能卡。本题仅仅用到总均摊数 \(O(n)\) 的结论,所以复杂度完全正确。假如是随机数据,则颜色段数量均摊为 \(O(\log{n})\),注意前者为总均摊,这里说的随机数据为每时每刻均摊。其实也比较好理解,如果我的 \([l,r]\) 够长,那么其实跑出来就跟随机数据差不多了,够短只用到了遍历,最坏也仅仅是趋近于暴力,有根号分治那个思想的味道了。

那么这样一来就可以轻松地处理出修改和查询离线数据,我们的 \(cdq\) 本质是处理偏序问题的,注意到其实还有一个序:\(时间序\),修改和查询的时间不能乱,这种序和数组下标序是差不多的,我们不需要刻意排序,直接按照对应的时间序下放就行。查询的时候,显然是 \(pre \le l-1\) 时,就加入 \(firstPos\) 这个点作为代表元贡献,其实可以看做就是一个带修版的 \(HH的项链\),树状数组查询贡献,注意我们的每个查询要写两部分,写成前缀和作差的形式。在带修的基础上,加入了化段为点的思想,最后注意一些细节,比如离散化,初始化加入初始数组的 \((pre_i,i)\) 贡献。

最后注意到一个问题,也是最难的一个问题,我们初始 \(ODT\) 里面都是 \((i,i,val)\) 段长为 \(1\),我们相同颜色段当做独立的,例如 \([1,1,1]\),可以看做 \(3\) 个极长连续段,那么初始的时候我们 \(l \rightarrow l-1\)\(pre\),则会像链表一样 \(1\leftarrow2\leftarrow3\)每个连续段颜色内部的 \(pre\) 是建好的,唯一需要建的则为 连接处\(l\rightarrow l-1\),它因为颜色覆盖变为了相同颜色,使得互相产生新的 \(pre\) 连接。

\(ODT\) 维护的段是连续的,只需要更改绿色部分的 \(pre\) 即可。顺便删除小段原有的贡献,这样之间的 \(pre\) 就正确了,再更改整段有关的 \(pre\) 就行了。其实删除操作,并不需要考虑当前段的 \(pre\) 变化,因为当前位置可能不再是代表元了,它的贡献已经无效的,如果加上,可能产生重复贡献,我们每个极长连续段只取开头元素作为代表元,相同颜色的连续段,我们规定长度为 \(1\) 即为极长连续段。

参照代码
#include <bits/stdc++.h>

// #pragma GCC optimize(2)
// #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4.1,sse4.2,avx,avx2,popcnt,tune=native")

#define isPbdsFile

#ifdef isPbdsFile

#include <bits/extc++.h>

#else

#include <ext/pb_ds/priority_queue.hpp>
#include <ext/pb_ds/hash_policy.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/trie_policy.hpp>
#include <ext/pb_ds/tag_and_trait.hpp>
#include <ext/pb_ds/hash_policy.hpp>
#include <ext/pb_ds/list_update_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/exception.hpp>
#include <ext/rope>

#endif

using namespace std;
using namespace __gnu_cxx;
using namespace __gnu_pbds;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef tuple<int, int, int> tii;
typedef tuple<ll, ll, ll> tll;
typedef unsigned int ui;
typedef unsigned long long ull;
typedef __int128 i128;
#define hash1 unordered_map
#define hash2 gp_hash_table
#define hash3 cc_hash_table
#define stdHeap std::priority_queue
#define pbdsHeap __gnu_pbds::priority_queue
#define sortArr(a, n) sort(a+1,a+n+1)
#define all(v) v.begin(),v.end()
#define yes cout<<"YES"
#define no cout<<"NO"
#define Spider ios_base::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
#define MyFile freopen("..\\input.txt", "r", stdin),freopen("..\\output.txt", "w", stdout);
#define forn(i, a, b) for(int i = a; i <= b; i++)
#define forv(i, a, b) for(int i=a;i>=b;i--)
#define ls(x) (x<<1)
#define rs(x) (x<<1|1)
#define endl '\n'
//用于Miller-Rabin
[[maybe_unused]] static int Prime_Number[13] = {0, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37};

template <typename T>
int disc(T* a, int n)
{
    return unique(a + 1, a + n + 1) - (a + 1);
}

template <typename T>
T lowBit(T x)
{
    return x & -x;
}

template <typename T>
T Rand(T l, T r)
{
    static mt19937 Rand(time(nullptr));
    uniform_int_distribution<T> dis(l, r);
    return dis(Rand);
}

template <typename T1, typename T2>
T1 modt(T1 a, T2 b)
{
    return (a % b + b) % b;
}

template <typename T1, typename T2, typename T3>
T1 qPow(T1 a, T2 b, T3 c)
{
    a %= c;
    T1 ans = 1;
    for (; b; b >>= 1, (a *= a) %= c)if (b & 1)(ans *= a) %= c;
    return modt(ans, c);
}

template <typename T>
void read(T& x)
{
    x = 0;
    T sign = 1;
    char ch = getchar();
    while (!isdigit(ch))
    {
        if (ch == '-')sign = -1;
        ch = getchar();
    }
    while (isdigit(ch))
    {
        x = (x << 3) + (x << 1) + (ch ^ 48);
        ch = getchar();
    }
    x *= sign;
}

template <typename T, typename... U>
void read(T& x, U&... y)
{
    read(x);
    read(y...);
}

template <typename T>
void write(T x)
{
    if (typeid(x) == typeid(char))return;
    if (x < 0)x = -x, putchar('-');
    if (x > 9)write(x / 10);
    putchar(x % 10 ^ 48);
}

template <typename C, typename T, typename... U>
void write(C c, T x, U... y)
{
    write(x), putchar(c);
    write(c, y...);
}


template <typename T11, typename T22, typename T33>
struct T3
{
    T11 one;
    T22 tow;
    T33 three;

    bool operator<(const T3 other) const
    {
        if (one == other.one)
        {
            if (tow == other.tow)return three < other.three;
            return tow < other.tow;
        }
        return one < other.one;
    }

    T3() { one = tow = three = 0; }

    T3(T11 one, T22 tow, T33 three) : one(one), tow(tow), three(three)
    {
    }
};

template <typename T1, typename T2>
void uMax(T1& x, T2 y)
{
    if (x < y)x = y;
}

template <typename T1, typename T2>
void uMin(T1& x, T2 y)
{
    if (x > y)x = y;
}

struct Hash
{
    static uint64_t splitmix64(uint64_t x)
    {
        x += 0x9e3779b97f4a7c15;
        x = (x ^ x >> 30) * 0xbf58476d1ce4e5b9;
        x = (x ^ x >> 27) * 0x94d049bb133111eb;
        return x ^ x >> 31;
    }

    static size_t get(const uint64_t x)
    {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }

    template <typename T>
    size_t operator()(T x) const
    {
        return get(std::hash<T>()(x));
    }

    template <typename F, typename S>
    size_t operator()(pair<F, S> p) const
    {
        return get(std::hash<F>()(p.first)) ^ std::hash<S>()(p.second);
    }
};

constexpr int N = 2e5 + 10;
int n, q;

struct Query
{
    int pre, firstPos, val, queryId;

    bool operator<(const Query& other) const
    {
        return pre < other.pre;
    }
} old[N], qu[N << 3];

int ans[N];
int mx, idx, queryIdx;

struct ODT
{
    int l, r;
    mutable int val;

    bool operator<(const ODT& other) const
    {
        return l < other.l;
    }
};

set<ODT> node; //ODT维护连续颜色段
set<pii> color[N]; //color颜色段桶
set<int> ord; //离散化
hash2<int, int, Hash> mp;
int pre[N], a[N];
//增加一个修改
inline void addUpdate(const int pos, const int val)
{
    qu[++idx] = Query(pre[pos], pos, val);
}

//pre变化
inline void updatePre(const int pos, const int prePos)
{
    addUpdate(pos, -1), pre[pos] = prePos, addUpdate(pos, 1);
}

//保证二者维护段的形态一致,方便做贡献修改
inline auto split(const int pos)
{
    auto it = node.lower_bound(ODT(pos, 0, 0));
    if (it != node.end() and it->l == pos)return it;
    --it;
    if (it->r < pos)return node.end();
    auto [l,r,val] = *it;
    color[val].erase(pii(l, r));
    color[val].insert(pii(l, pos - 1)), color[val].insert(pii(pos, r));
    node.erase(it), node.insert(ODT(l, pos - 1, val));
    return node.insert(ODT(pos, r, val)).first;
}

//变化前后
inline void add(const int c, const int l, const int r)
{
    auto& curr = color[c];
    auto it = curr.lower_bound(pii(l, 0));
    if (it != curr.end())updatePre(it->first, r); //在它之后的更新第一个的pre
    int prePos = 0;
    if (it != curr.begin())--it, prePos = it->second; //在它之前的让当前第一个位置l的pre变为它,否则为0
    updatePre(l, prePos);
    curr.insert(pii(l, r));
}

//变化后面的
inline void del(const int c, const int l, const int r)
{
    //删除只有在它之后的位置的pre发生了变化
    auto& curr = color[c];
    curr.erase(pii(l, r));
    auto it = curr.lower_bound(pii(l, 0));
    if (it == curr.end())return; //在它之后没有的就不更新了
    int prePos = 0;
    auto [L,R] = *it;
    if (it != curr.begin())--it, prePos = it->second;
    updatePre(L, prePos); //在它之后的那个段开头更新为前一个剩余段的开头
}

int bit[N];

inline void add(int x, const int val)
{
    while (x <= n)bit[x] += val, x += lowBit(x);
}

inline int query(int x)
{
    int ans = 0;
    while (x)ans += bit[x], x -= lowBit(x);
    return ans;
}

inline void cdq(const int L, const int R)
{
    const int mid = L + R >> 1;
    if (L == R)return;
    cdq(L, mid), cdq(mid + 1, R);
    stable_sort(qu + L, qu + mid + 1), stable_sort(qu + mid + 1, qu + R + 1);
    int l = L;
    forn(r, mid+1, R)
    {
        auto [qL,qR,val,queryId] = qu[r];
        if (!queryId)continue;
        while (l <= mid and qu[l].pre <= qL)
        {
            if (!qu[l].queryId)add(qu[l].firstPos, qu[l].val);
            l++;
        }
        ans[queryId] += query(qR) * val;
    }
    forn(i, L, l-1)if (!qu[i].queryId)add(qu[i].firstPos, -qu[i].val);
}

int pos[N];

inline void solve()
{
    cin >> n >> q;
    forn(i, 1, n)cin >> a[i], ord.insert(a[i]);
    forn(i, 1, q)
    {
        auto& [l,r,val,op] = old[i];
        cin >> op >> l >> r;
        if (op == 1)cin >> val, ord.insert(val);
    }
    for (const auto v : ord)mp[v] = ++mx; //离散化
    forn(i, 1, n)
    {
        a[i] = mp[a[i]];
        node.insert(ODT(i, i, a[i]));
        if (pos[a[i]])pre[i] = pos[a[i]];
        pos[a[i]] = i;
        color[a[i]].insert(pii(i, i));
        addUpdate(i, 1); //初始数组的(pre[i],i)贡献
    }
    forn(i, 1, q)
    {
        auto& [l,r,val,op] = old[i];
        if (op == 1)
        {
            val = mp[val];
            auto itR = split(r + 1), itL = split(l);
            //每一个和它前面的段进行修改pre
            auto it = itL;
            del(it->val, it->l, it->r); //第一个段的pre是在之前的了
            //这里比较有意思,初始是1的段长,覆盖时自然而然就会连接了
            for (++it; it != itR; ++it)updatePre(it->l, it->l - 1), del(it->val, it->l, it->r);
            node.erase(itL, itR), node.insert(ODT(l, r, val));
            add(val, l, r);
        }
        else
        {
            //前缀和作差,Ans(0~r)-Ans(0~l-1)
            //pre<l =>pre<=l-1
            qu[++idx] = Query(l - 1, r, 1, ++queryIdx);
            qu[++idx] = Query(l - 1, l - 1, -1, queryIdx);
        }
    }
    cdq(1, idx);
    forn(i, 1, queryIdx)cout << ans[i] << endl;
}

signed int main()
{
    // MyFile
    Spider
    //------------------------------------------------------
    // clock_t start = clock();
    int test = 1;
    //    read(test);
    // cin >> test;
    forn(i, 1, test)solve();
    //    while (cin >> n, n)solve();
    //    while (cin >> test)solve();
    // clock_t end = clock();
    // cerr << "time = " << double(end - start) / CLOCKS_PER_SEC << "s" << endl;
}

\[时间复杂度为:\ O(n\log^2{V_{max}}) \]

posted @ 2024-03-01 18:57  Athanasy  阅读(32)  评论(0编辑  收藏  举报