链接:https://www.nowcoder.com/acm/contest/139/J
来源:牛客网
题目描述
Given a sequence of integers a1, a2, ..., an and q pairs of integers (l1, r1), (l2, r2), ..., (lq, rq), find count(l1, r1), count(l2, r2), ..., count(lq, rq) where count(i, j) is the number of different integers among a1, a2, ..., ai, aj, aj + 1, ..., an.
输入描述:
The input consists of several test cases and is terminated by end-of-file.
The first line of each test cases contains two integers n and q.
The second line contains n integers a1, a2, ..., an.
The i-th of the following q lines contains two integers li and ri.
输出描述:
For each test case, print q integers which denote the result.
示例1
输入
3 2
1 2 1
1 2
1 3
4 1
1 2 3 4
1 3
输出
2
1
3
备注:
* 1 ≤ n, q ≤ 105
* 1 ≤ ai ≤ n
* 1 ≤ li, ri ≤ n
* The number of test cases does not exceed 10.
题意:
查询区间除了(l,r)区间内元素,其他序列元素的不重复数个数。
思路:
将数组倍增一遍,将不连续区间变为连续区间。
在用树状数组查询区间不同数个数,对要查询区间进行离线处理,按照r从小到大排序处理。
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+100;
int n,q,a[N*2],sum[N*2],vis[N*2],c[N*2];
struct Node
{
int x,y,index;
bool operator < (const Node&other)const
{
return y<other.y;
}
}node[N*2];
int lowbit(int i)
{
return i&(-i);
}
void add(int x,int value)
{
while(x<N*2)
{
c[x]+=value;
x+=lowbit(x);
}
}
int query(int x)
{
int ans=0;
while(x>0)
{
ans+=c[x];
x-=lowbit(x);
}
return ans;
}
int main()
{
while(~scanf("%d%d",&n,&q))
{
int i,j,xx,yy;
memset(vis,0,sizeof(vis));
memset(sum,0,sizeof(sum));
memset(c,0,sizeof(c));
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
a[i+n]=a[i];
}
for(i=1;i<=q;i++)
{
scanf("%d%d",&xx,&yy);
node[i].x=yy;
node[i].y=n+xx;
node[i].index=i;
}
sort(node+1,node+q+1);
//for(i=1;i<=q;i++)
//cout<<node[i].x<<" "<<node[i].y<<" "<<node[i].index<<endl;
int cnt=1;
for(i=1;i<=2*n&&cnt<=q;i++)
{
if(vis[a[i]])
add(vis[a[i]],-1);
vis[a[i]]=i;
add(vis[a[i]],1);
//cout<<"!! "<<cnt<<" "<<i<<" "<<node[cnt].y<<endl;
while(cnt<=q&&i>=node[cnt].y)
{
//cout<<"! "<<query(node[cnt].y)<<" "<<query(node[cnt].x-1)<<endl;
sum[node[cnt].index]=query(node[cnt].y)-query(node[cnt].x-1);
cnt++;
//cout<<"!!! "<<cnt<<" "<<i<<endl;
}
}
for(i=1;i<=q;i++)
printf("%d\n",sum[i]);
}
return 0;
}