51nod 1001 数组中和等于K的数对

给出一个整数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

开一个map判断一下k-a[i]是否存在

#include<map>
#include<cstdio>
#include<algorithm>
using namespace std;
map<int,bool>mp;
int a[500003];
int main(){
    int k,n,cnt=0;;
    scanf("%d%d",&k,&n);
    for(int i=1;i<=n;i++) scanf("%d",a+i),mp[k-a[i]]=1;
    sort(a+1,a+n+1);
	for(int i=1;i<=n;++i)
    int cnt=0;
    for(int i=1;i<=n;i++) {
    	if(mp[a[i]]) {
    		if(a[i]>=k-a[i])break;
    		cnt++,printf("%d %d
",a[i],k-a[i]);
		}
	}
    if(cnt==0) puts("No Solution");
    return 0;
}
原文地址:https://www.cnblogs.com/sssy/p/7732470.html