![](http://acm.fzu.edu.cn/image/problem.gif)
Accept: 229 Submit: 1131
Time Limit: 1000 mSec Memory Limit : 32768 KB
Problem Description
A array contain N number, can you tell me how many different pair i,j that satisfy a[i] + a[j] = M and 1<=i < j <=N.
Input
There are multiple tests,
each test first line contain two integer numbers N M, second line contain N integer numbers.
0 < N <= 100000, 0 <= M <= 1000000000, -1000000000 <= a[i] <= 1000000000
Output
Each test output how many different pair i,j that satisfy a[i] + a[j] = M and 1<=i < j <=N .
Sample Input
3 21 1 15 51 2 3 4 5
Sample Output
32
Source
FOJ有奖月赛-2011年11月
思路:
其实问题就是在统计,对应到位子i,其前边出现了多少个m-a【i】这个数。
对应统计起来即可。
可惜Fzu自带卡Map功能。
那么哦们不妨离散化一下,将a【i】和m-a【i】一共2*n个数进行离散化,然后再统计即可。
Ac代码:
#include<stdio.h>
#include<string.h>
#include<map>
#include<algorithm>
using namespace std;
struct node
{
int val,id,pos;
}a[250000];
int vis[250000];
int n,m;
int cmp(node a,node b)
{
return a.val<b.val;
}
int cmp2(node a,node b)
{
return a.pos<b.pos;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i].val);
a[i+n].val=m-a[i].val;
a[i].pos=i;
a[i+n].pos=i+n;
}
sort(a+1,a+1+2*n,cmp);
for(int i=1;i<=2*n;i++)
{
if(i==1)
a[i].id=1;
else
{
if(a[i].val==a[i-1].val)a[i].id=a[i-1].id;
else a[i].id=a[i-1].id+1;
}
}
__int64 output=0;
sort(a+1,a+1+2*n,cmp2);
for(int i=1;i<=n;i++)
{
output+=vis[a[i+n].id];
vis[a[i].id]++;
}
printf("%I64d\n",output);
}
}