Description
给出一个长度为n的序列a[]
给出q组询问,每组询问形如(x,y),求a序列的所有区间中,数字x的出现次数与数字y的出现次数相同的区间有多少个
Input
第一行两个数n和q
第二行n个数a[i]
接下来q行,每行两个数x,y表示一组询问
Output
q行,每行一个数表示对应询问的答案
Sample Input
3 2
1 2 1
1 2
4 5
Sample Output
2
6
Data Constraint
对于30%的数据,1<=n<=100,1<=q<=1000
对于另外30%的数据,序列中只有最多50种不同的颜色且1<=n<=1000
对于100%的数据,1<=n<=8000,1<=q<=500000,1<=x,y,a[i]<=10^9
题解
因为要求区间,自然想到前缀和。
从头开始枚举,遇到x就+1,遇到y就-1,
那么前缀和相同的都棵两两构成一个区间。
如果对于每个询问都O(n)枚举前缀和,
那样是过不了的。
可以发现,这个前缀和只与x和y的位置有关。
对于每一个数,都可以维护一个数,表示下一个与它相同的数在哪里。
code
#include<queue>
#include<cstdio>
#include<iostream>
#include<algorithm>
#include <cstring>
#include <string.h>
#include <cmath>
#include <math.h>
#define ll long long
#define N 8003
#define db double
#define P putchar
#define G getchar
#define mo 23333
using namespace std;
char ch;
void read(int &n)
{
n=0;
ch=G();
while((ch<