跳到正文

题解

题解:P7764 [COCI 2016/2017 #5] Poklon

W1nterx_约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年7月22日
篇幅
约 3 分钟
获赞
1
题目
P7764

版本

  1. v1当前

前置知识

莫队,离散化

PS:其实就是莫队模板题

题意分析

求区间[l,r]中恰好出现两次的数字有几个

可以用莫队做

话不多说上代码

代码

C++
#include<bits/stdc++.h>
using namespace std;
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;
}
#define fi first
#define se second
#define lc x<<1
#define rc x<<1|1
typedef long long ll;
typedef pair<int,int> pa;

const int N=5e5+5;

struct Query{
	int l,r,id;
}Q[N];

int n,q,Block;
int a[N],cnt[N],res[N];
int ans;

bool cmp(Query a,Query b){
	int blockA=(a.l-1)/Block,blockB=(b.l-1)/Block;
	if(blockA!=blockB)return blockA<blockB;
	return a.r<b.r; 
}

void Add(int x){
	if(cnt[x]==2)ans--;
	cnt[x]++;
	if(cnt[x]==2)ans++;
}

void Remove(int x) {
	if(cnt[x]==2)ans--;
	cnt[x]--;
	if(cnt[x]==2)ans++;
}

int main() {
	n=read(),q =read();
	Block=sqrt(n);
	for(int i=1;i<=n;i++){
		a[i]=read();
	}
	for(int i=1;i<=q;i++){
		int l=read(),r=read();
		Q[i]={l,r,i};
	}
	sort(Q+1,Q+q+1,cmp);
	int l=1,r=0;
	for(int i=1;i<=q;i++){
		while(l<Q[i].l)Remove(a[l]),l++;
		while(l>Q[i].l)l--,Add(a[l]);
		while(r<Q[i].r)r++,Add(a[r]);
		while(r>Q[i].r)Remove(a[r]),r--;
		res[Q[i].id]=ans;
	}
	for(int i=1;i<=q;i++){
		printf("%d\n",res[i]);
	}
	return 0;
}
原文