洛谷-P5906 【模板】回滚莫队&不删除莫队

时间:2022-05-26
本文章向大家介绍洛谷-P5906 【模板】回滚莫队&不删除莫队,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

【模板】回滚莫队&不删除莫队

回滚莫队 模板题

最近状态挺差的,本来就应该一遍过,但是愣是出了很多很不应该的错误

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
#define endl '\n'
const int maxn = 2e5 + 10;
int a[maxn], num[maxn], id[maxn], pos[maxn];
int cnt_r[maxn], cnt_l[maxn], cnt_p[maxn];
int last[maxn];

struct node
{
    int l, r, id;
    node(){}
    node(int _l, int _r, int _id){l = _l; r = _r; id = _id;}
}seg[maxn];

bool cmp(const node& a, const node& b)
{
    return pos[a.l] ^ pos[b.l] ? pos[a.l] < pos[b.l] : a.r < b.r;
}

int main()
{
    ios::sync_with_stdio(false);
    cout.tie(0);
    cin.tie(0);
    // freopen("text.in", "rb", stdin);
    // freopen("text.out", "wb", stdout);
    int n, m;
    cin >> n;
    for(int i=1; i<=n; i++)
    {
        cin >> num[i];
        a[i] = num[i];
    }
    sort(a + 1, a + 1 + n);
    int tp = unique(a + 1, a + n + 1) - a - 1;
    for(int i=1; i<=n; i++)
        num[i] = lower_bound(a + 1, a + tp + 1, num[i]) - a;
    
    cin >> m;
    for(int i=0; i<m; i++)
    {
        int x, y;
        cin >> x >> y;
        seg[i] = node(x, y, i);
    }
    int t = max(1, (int)(n / sqrt(m)));
    for(int i=1; i<=n; i++) pos[i] = i / t + 1;
    sort(seg, seg + m, cmp);
    
    int l = 1, r = 0, pre_b = -1, ans = 0;
    for(int i=0; i<m; i++)
    {
        if(pre_b != pos[seg[i].l])
        {
            pre_b = pos[seg[i].l];
            for(int j=l; j<=r; j++) cnt_l[num[j]] = cnt_r[num[j]] = 0;
            l = pre_b * t;
            r = l - 1;
            ans = 0;
        }
        if(pos[seg[i].l] == pos[seg[i].r])
        {
            for(int j=seg[i].l; j<=seg[i].r; j++)
            {
                if(cnt_l[num[j]] == 0) cnt_l[num[j]] = j;
                cnt_r[num[j]] = j;
                ans = max(cnt_r[num[j]] - cnt_l[num[j]], ans);
            }
            last[seg[i].id] = ans;
            for(int j=seg[i].l; j<=seg[i].r; j++)
                cnt_l[num[j]] = cnt_r[num[j]] = 0;
            ans = 0;
            continue;
        }
        while(seg[i].r > r)
        {
            r++;
            if(cnt_l[num[r]] == 0) cnt_l[num[r]] = r;
            cnt_r[num[r]] = r;
            ans = max(ans, cnt_r[num[r]] - cnt_l[num[r]]);
        }
        int temp = ans, x = l;
        while(seg[i].l < l)
        {
            l--;
            if(cnt_p[num[l]] == 0) cnt_p[num[l]] = l;
            ans = max(ans, max(cnt_p[num[l]], cnt_r[num[l]]) - l);
        }
        last[seg[i].id] = ans;
        while(l < x)
        {
            cnt_p[num[l]] = 0;
            l++;
        }
        ans = temp;
    }
    for(int i=0; i<m; i++)
        cout << last[i] << endl;
    return 0;
}

原文地址:https://www.cnblogs.com/dgsvygd/p/16315153.html