SPOJ-DQUERY-D-query

Posted ydddd

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SPOJ-DQUERY-D-query相关的知识,希望对你有一定的参考价值。

链接:

https://vjudge.net/problem/SPOJ-DQUERY

题意:

找n个数中无修改的区间不同数个数

思路:

莫队算法,第一次写,很奇怪,代码很好写,分块之后来回跳。

代码:

#include <iostream>
#include <cstdio>
#include <vector>
#include <memory.h>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <math.h>
#include <stack>
using namespace std;
typedef long long LL;
const int MAXN = 3e4+10;
const int MAXQ = 2e5+10;

struct Node

    int v;
    int pos;
    bool operator < (const Node& that) const
    
        return this->v < that.v;
    
node[MAXN];
struct QueryNode

    int l, r;
    int id;
querynode[MAXQ];
int Sec[MAXN];
int Vis[MAXN];
int Res[MAXQ];
int n, q;
int l, r, res;
int unit;

bool cmp(QueryNode a, QueryNode b)

    if (a.l/unit != b.l/unit)
        return a.l/unit < b.l/unit;
    return a.r < b.r;


void Add(int pos)

    if (!Vis[pos])
        res++;
    Vis[pos]++;


void Del(int pos)

    Vis[pos]--;
    if (!Vis[pos])
        res--;


void Query(int ql, int qr)

    while (l < ql)
        Del(Sec[l++]);
    while (l > ql)
        Add(Sec[--l]);
    while (r < qr)
        Add(Sec[++r]);
    while (r > qr)
        Del(Sec[r--]);


void Sectter()

    sort(node+1, node+1+n);
    int cnt = 0;
    Sec[node[1].pos] = ++cnt;
    for (int i = 2;i <= n;i++)
    
        if (node[i-1].v == node[i].v)
            Sec[node[i].pos] = cnt;
        else
            Sec[node[i].pos] = ++cnt;
    


int main()

    scanf("%d", &n);
    unit = sqrt(n);
    for (int i = 1;i <= n;i++)
        scanf("%d", &node[i].v), node[i].pos = i;
    Sectter();
    scanf("%d", &q);
    for (int i = 1;i <= q;i++)
        scanf("%d %d", &querynode[i].l, &querynode[i].r), querynode[i].id = i;
    sort(querynode+1, querynode+1+q, cmp);
    l = 1, r = 0, res = 0;
    for (int i = 1;i <= q;i++)
    
        Query(querynode[i].l, querynode[i].r);
        Res[querynode[i].id] = res;
    
    for (int i = 1;i <= q;i++)
        printf("%d\n", Res[i]);

    return 0;

以上是关于SPOJ-DQUERY-D-query的主要内容,如果未能解决你的问题,请参考以下文章