标签:== 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;
}
标签:== type lse const his 莫队算法 print hat cto
原文地址:https://www.cnblogs.com/YDDDD/p/11219736.html