题目大意
给出长为n的序列a,m个询问l,r,p,q,问l到r中有多少个数满足mod p=q。
n,m<=100000,a,p,q<=10000
时间限制 1s
空间限制 256M
解题思路
把询问l,r,p,q拆分成询问r,p,q和l-1,p,q,再将这些询问排序后单独求解。
维护两个数组h[i]和g[i][j],h[i]表示i这个数出现了多少次,g[i][j]表示有多少个数满足mod i=j。
每加入一个数,就更新h和g
对于询问l,r,p,q,如果p<=100,就直接在g数组中求解;否则枚举k,把所有h[k*p+q]加起来就是答案。
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxn 100006
#define fr(i,a,b) for(i=a;i<=b;i++)
using namespace std;
typedef long long ll;
struct nod
{
int l,r,p,q,s[2];
} Q[maxn];
struct node
{
int x,y,z;
} d[maxn+maxn];
bool cmp(node a,node b)
{
return a.x<b.x;
}
int i,j,k,n,m,t,mx,tot,ans,a[maxn],h[10006],g[106][106];
int main()
{
scanf("%d%d",&n,&m);
fr(i,1,n) scanf("%d",&a[i]),mx=max(mx,a[i]);
fr(i,1,m)
{
scanf("%d%d%d%d",&Q[i].l,&Q[i].r,&Q[i].p,&Q[i].q);
d[++tot].x=Q[i].l-1,d[tot].y=i,d[tot].z=0;
d[++tot].x=Q[i].r,d[tot].y=i,d[tot].z=1;
}
sort(d+1,d+tot+1,cmp);
fr(i,1,tot)
{
ans=0;
while (j<d[i].x)
{
t=a[++j];
// if (t<=100)
fr(k,1,100) g[k][t%k]++;
h[t]++;
}
int l=Q[d[i].y].l,r=Q[d[i].y].r,p=Q[d[i].y].p,q=Q[d[i].y].q;
if (p<=100) ans=g[p][q];
else
{
fr(k,0,100)
if (k*p+q<=mx)
ans+=h[k*p+q];
else break;
}
Q[d[i].y].s[d[i].z]=ans;
}
fr(i,1,m)
{
ans=Q[i].s[1]-Q[i].s[0];
printf("%d\n",ans);
}
return 0;
}