题目:http://acm.hdu.edu.cn/showproblem.php?pid=5213
Lucky
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 763 Accepted Submission(s): 249
If WLD can answer all the questions correctly,he'll be the luckiest man in the world.Can you help him?
For each case:
The first line contains an integer N(1≤N≤30000).
The following line contains an integer K(2≤K≤2∗N),WLD's lucky number.K is odd.
The following line contains N integers a1,a2,...,aN(1≤ai≤N).
The following line contains an integer M(1≤M≤30000),the sum of the questions WLD has to answer.
The following M lines,the i-th line contains 4 numbers Li,Ri,Ui,Vi(1≤Li≤Ri<Ui≤Vi≤N),describing the i-th question the stranger asks.
Print the total of pairs WLD can choose for each question.
3
1 2 1 2 3
1
1 2 3 5
a1+a4=a2+a3=3=K.
So we have two pairs of numbers (1,4) and (2,3).
Good luck!
#include<bits/stdc++.h>
using namespace std;
#define MAXN 30010
#define MAXM 30010
struct node
{
int l,r,id,fh;
}q[MAXM*];
int a[MAXN],pos[MAXN],sum[MAXN*],N,ans[MAXM*];
int read()
{
int s=,fh=;char ch=getchar();
while(ch<''||ch>''){if(ch=='-')fh=-;ch=getchar();}
while(ch>=''&&ch<=''){s=s*+(ch-'');ch=getchar();}
return s*fh;
}
void Add(int ll,int rr,int ii,int ff){q[++N].l=ll;q[N].r=rr;q[N].id=ii;q[N].fh=ff;}
bool cmp(node aa,node bb)
{
if(pos[aa.l]==pos[bb.l])return aa.r<bb.r;
return aa.l<bb.l;
}
int main()
{
int n,k,i,m,block,tot,L,R,U,V;
while(scanf("%d",&n)!=EOF)
{
k=read();
for(i=;i<=n;i++)a[i]=read();
m=read();
N=;
for(i=;i<=m;i++)
{
L=read();R=read();U=read();V=read();
Add(L,V,i,);Add(L,U-,i,-);Add(R+,V,i,-);Add(R+,U-,i,);
}
block=(int)sqrt(n);
for(i=;i<=n;i++)pos[i]=(int)(i-)/block+;
sort(q+,q+N+,cmp);
memset(ans,,sizeof(ans));
L=;R=;
tot=;//当前区间有多少对a[i]+a[j]=k.
memset(sum,,sizeof(sum));//当前区间数字为i的有sum[i]个.
for(i=;i<=N;i++)
{
while(L<q[i].l)
{
sum[a[L]]--;
tot-=sum[k-a[L]];
//sum[a[L]]--;
//if(k==a[L]*2)tot++;
L++;
}
while(L>q[i].l)
{
L--;
tot+=sum[k-a[L]];
sum[a[L]]++;
}
while(R<q[i].r)
{
R++;
tot+=sum[k-a[R]];
sum[a[R]]++;
}
while(R>q[i].r)
{
sum[a[R]]--;
tot-=sum[k-a[R]];
//sum[a[R]]--;
//if(k==a[R]*2)tot++;
R--;
}
ans[q[i].id]+=q[i].fh*tot;
}
for(i=;i<=m;i++)printf("%d\n",ans[i]);
}
fclose(stdin);
fclose(stdout);
return ;
}