DQUERY - D-query
题意大致是这样的:
给定一段数列。
Q次询问,每次询问一个区间内有多少不同的数字。
非常经典的莫队题。
套用莫队模板,但是要维护的now值有所不同。
我们要维护的是这段区间内有多少不同的数字。
显然,我们可以判断这个是否在这段区间内只出现了1次。
具体来说:
如果只出现了1次,就可以使now+1。
如果是删除操作,那么在删除前先判断这个数字出现了几次。
如果只出现了1次,说明删除后区间中将不存在该数字,使now-1。
AC代码
#include<bits/stdc++.h>
using namespace std;
const int N=1010000;
int n, q, len, now;
int a[N], cnt[N], ans[N];
struct node {
int l, r, id, b;
} e[N];
void add(int x) {
if(!cnt[a[x]]) ++now;
++cnt[a[x]];
}
void del(int x) {
--cnt[a[x]];
if(!cnt[a[x]]) --now;
}
bool cmp(node a, node b) {
return (a.b ^ b.b) ? a.b < b.b : (a.b & 1 ? a.r < b.r : a.r > b.r);
}
inline int read(){int x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0' && ch<='9')x=x*10+ch-'0',ch=getchar();return x*f;}
void write(int x){if(x<0)putchar('-'),x=-x;if(x>9)write(x/10);putchar(x%10+'0');return;}
int main() {
n=read();
len = sqrt(n);
for(int i = 1; i <= n; ++i) a[i] = read();
q = read();
for(int i = 1; i <= q; ++i) {
e[i].l = read(), e[i].r = read();
e[i].id = i;
e[i].b = ceil(e[i].l / len);
}
sort(e + 1, e + q + 1, cmp);
int l = 1, r = 0;
for(int i = 1; i <= q; ++i) {
int x = e[i].l, y = e[i].r;
while(l < x) del(l++);
while(l > x) add(--l);
while(r < y) add(++r);
while(r > y) del(r--);
ans[e[i].id] = now;
}
for(int i = 1; i <= q; ++i){
write(ans[i]);
puts("");
}
return 0;
}
P3901 数列找不同
和上一题思路基本相同。
只不过要查询的变成了这段区间中是否没有相同的数字。
设pos为该区间中有多少数出现次数大于1。
当pos为0时,输出Yes,否则输出No即可。
我们只需要将判断改为:
当添加前已经有这个数字了,pos+1。
当删除后发现这个数字唯一了,pos-1。
依据pos决定输出的内容即可。
AC代码
#include<bits/stdc++.h>
using namespace std;
const int N=101000;
int n,q,len,x,y,pos;
int a[N],cnt[N],ans[N];
struct node{
int l,r,id,b;
}e[N];
bool cmp(node a,node b){
return (a.b ^ b.b) ? a.b < b.b : (a.b & 1 ? a.r < b.r : a.r > b.r);
}
void add(int x){
if(cnt[a[x]]==1) pos++;
cnt[a[x]]++;
}
void remove(int x){
cnt[a[x]]--;
if(cnt[a[x]]==1) pos--;
}
inline int read(){int x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0' && ch<='9')x=x*10+ch-'0',ch=getchar();return x*f;}
void write(int x){if(x<0)putchar('-'),x=-x;if(x>9)write(x/10);putchar(x%10+'0');return;}
int main() {
n=read();q=read();
for(int i=1;i<=n;i++) a[i]=read();
len=sqrt(n);
for(int i=1;i<=q;i++){
e[i].l=read();
e[i].r=read();
e[i].id=i;
e[i].b=ceil(e[i].l/len);
}
sort(e+1,e+1+q,cmp);
int l=1,r=0;
for(int i=1;i<=q;i++){
x=e[i].l;y=e[i].r;
while(l<x) remove(l++);
while(l>x) add(--l);
while(r<y) add(++r);
while(r>y) remove(r--);
if(pos==0){
ans[e[i].id]=1;
}
}
for(int i=1;i<=q;i++){
if(ans[i]==1) puts("Yes");
else puts("No");
}
return 0;
}