Time limit: 2 seconds for C / C + + and 4 seconds for other languages
Space limitation: C/C++ 131072K, other languages 262144 K
64bit IO Format: %lld
Title Description
Read in an integer sequence a1,a2 , an, and an integer K.
Group q asked.
Each group of queries contains a tuple (l, r), where 1 ≤ l ≤ r ≤ n,
Find the number of all the tuples (l2, r2) that meet the following conditions:
1: 1≤l≤l2≤r2≤r≤n,
2: It's a multiple of k.
Enter a description:
The first line is an integer T, indicating that there are t groups of data.
For each set of data,
In the first line, enter three integers, n, q, k,
Next, enter n integers, a1,a2 an,
Next line q, enter 2 integers l, r for each line
Output Description:
For each query, the number of bytes (l2,r2) satisfying the condition is output.
Example 1
input
1
5 2 4
4 1 4 8 8
2 2
2 4
output
0
3
Explain
When (l, r) is (2, 4),
Yes
(l2,r2)=(3,4),a3+a4=12, which is a multiple of 4
(l2,r2)=(3,3),a3=4, which is a multiple of 4
(l2,r2)=(4,4),a4=8, which is a multiple of 4
remarks:
1≤ n,q ≤5×104,
1≤ l ≤ r ≤n,
1≤ ai, k ≤109,
Ensure that Σ n ≤ 6 × 104, Σ q ≤ 6 × 104
Code
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MAXN = 5e4+11;
int sum[MAXN];
int HASH[MAXN],sz; // dispersed
int pos[MAXN],limit; //Blocking
struct Query{
int l,r,id;
}Q[MAXN+1];
bool cmp(Query a,Query b){
if(pos[a.l]!=pos[b.l]) return pos[a.l]<pos[b.l];
else return a.r<b.r;
}
LL Cnt[MAXN+1],Ans[MAXN]; LL ans;
void UpDate(int x){
ans+=Cnt[sum[x]];
Cnt[sum[x]]++;
}
void Delete(int x){
Cnt[sum[x]]--;
ans-=Cnt[sum[x]];
}
void solve(int m){
for(int i=1;i<=m;i++){ scanf("%d%d",&Q[i].l,&Q[i].r);Q[i].id=i; }
sort(Q+1,Q+1+m,cmp);
memset(Cnt,0,sizeof(Cnt));
ans=0; int L=1,R=0;
for(int i=1;i<=m;i++){
int id=Q[i].id;
while(R<Q[i].r) UpDate(++R);
while(L>Q[i].l) UpDate(--L);
while(R>Q[i].r) Delete(R--);
while(L<Q[i].l) Delete(L++);
Ans[id]=ans+Cnt[sum[Q[i].l-1]];
}
for(int i=1;i<=m;i++) printf("%lld\n",Ans[i]);
}
int main(){
int T;scanf("%d",&T);
while(T--){
int n,m,k;scanf("%d%d%d",&n,&m,&k);
limit=ceil(sqrt(n*1.0)); sz=0;
HASH[sz++]=0; sum[0]=0;
for(int i=1;i<=n;i++){
scanf("%d",&sum[i]);
sum[i]=sum[i-1]+sum[i];
sum[i]%=k; pos[i]=(i-1)/limit; HASH[sz++]=sum[i];
}
sort(HASH,HASH+sz); sz=unique(HASH,HASH+sz)-HASH;
for(int i=0;i<=n;i++) sum[i]=lower_bound(HASH,HASH+sz,sum[i])-HASH+1;
//for(int i=0;i<=n;i++) printf("%d ",sum[i]);
solve(m); // Mo team
}
return 0;
}