码迷,mamicode.com
首页 > 其他好文 > 详细

SPOJ-DQUERY-D-query

时间:2019-07-21 01:23:05      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:==   type   lse   const   his   莫队算法   print   hat   cto   

链接:

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

标签:==   type   lse   const   his   莫队算法   print   hat   cto   

原文地址:https://www.cnblogs.com/YDDDD/p/11219736.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!