链接:https://ac.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.
n个数,q次询问,给你l r 两个数 问你1-l和r-n这两个区间有多少个不同的数
考虑离线树状数组,将数列长度扩大一倍
比如 1 2 3 4 扩大一倍变为 1 2 3 4 1 2 3 4 那么问题就转化为n+l~r区间有多少个不同的数,经典问题
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn=2e5+5;
int c[maxn],a[maxn],ans[maxn],n,m;
inline int lowbit(int x){return x&(-x);}
inline void update(int i,int val){while(i<=n){c[i]+=val;i+=lowbit(i);}}
inline int query(int i){int res=0;while(i>0){res+=c[i];i-=lowbit(i);}return res;}
unordered_map<int,int>mp;
std::vector<pair<int,pair<int,int> > > q;;
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=0;i<=2*n;i++)c[i]=ans[i]=a[i]=0;
mp.clear();q.clear();int p=n;
for(int i=1;i<=n;i++){scanf("%d",&a[i]);a[i+n]=a[i];}n*=2;
for(int i=0;i<m;i++)
{
int l,r;scanf("%d%d",&l,&r);
q.emplace_back(make_pair((p+l),make_pair(r,i)));
}
sort(q.begin(),q.end());int cnt=1;
for(int i=0;i<m;i++)
{
while(cnt<=q[i].first)
{
if(mp[a[cnt]])update(mp[a[cnt]],-1);
update(mp[a[cnt]]=cnt,1);cnt++;
}
ans[q[i].second.second]=query(q[i].first)-query(q[i].second.first-1);
}
for(int i=0;i<m;i++)printf("%d\n",ans[i]);
}
return 0;
}
本文介绍了一种使用离线树状数组解决区间内不同整数计数问题的方法。通过将原始数列长度加倍并利用树状数组的数据结构特性,可以有效地处理批量区间查询,计算每个区间内的不同整数数量。适用于编程竞赛中的数据结构与算法题型。
662

被折叠的 条评论
为什么被折叠?



