您的位置:首页 > 其它

[51NOD] 1001 数组中和等于K的数对 [二分]

2017-02-26 15:57 218 查看
给出一个整数K和一个无序数组A,A的元素为N个互不相同的整数,找出数组A中所有和等于K的数对。例如K = 8,数组A:{-1,6,5,3,4,2,9,0,8},所有和等于8的数对包括(-1,9),(0,8),(2,6),(3,5)。

Input

第1行:用空格隔开的2个数,K N,N为A数组的长度。(2 <= N <= 50000,-10^9 <= K <= 10^9)

第2 - N + 1行:A数组的N个元素。(-10^9 <= A[i] <= 10^9)

Output

第1 - M行:每行2个数,要求较小的数在前面,并且这M个数对按照较小的数升序排列。

如果不存在任何一组解则输出:No Solution。

Input示例

8 9

-1

6

5

3

4

2

9

0

8

Output示例

-1 9

0 8

2 6

3 5

#include<stdio.h>
#include<algorithm>
#define MAX_N 50005
using namespace std;
int a[MAX_N];

int main()
{
int N,M;
scanf("%d%d",&N,&M);
for(int i=0;i<M;i++)
scanf("%d",&a[i]);
sort(a,a+M);
bool flag=false;
for(int i=0;2*a[i]<N;i++){
int t=N-a[i];
int *f=lower_bound(a,a+M,t);
if(t==*f){
printf("%d %d\n",a[i],t);
flag=true;
}
}
if(!flag) puts("No Solution");
return 0;
}


题目链接

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1001
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: