given an integer k and an unordered array, the elements of a,a are n distinct integers, finding the pairs of all and equal k in array a. For example k = 8, Array a:{-1,6,5,3,4,2,9,0,8}, all and equal to 8 pairs include ( -1,9), (0,8), (2,6), (3,5). Input
Line 1th: 2 numbers separated by a space, K n,n is the length of a array. (2 <= n <= 50000,-10^9 <= K <= 10^9) Section 2-n + 1 rows: N elements of a array. ( -10^9 <= a[i] <= 10^9)
Output
Line 1-m: 2 numbers per line, requires a smaller number in front, and the m number is in ascending order of smaller numbers. If there is no one set of solutions output: no solution.
Input Example
8 9-165342908
Output Example
-1 90 82 63 5
One is to sort first, find from scratch, and find k-a[i] in the sequence.
The second is to gradually look at both ends, gradually narrowing the range, the next number of the range must be within the previous
Code:
#include <stdio.h>#include<iostream>#include<algorithm>using namespacestd;Const intMAXN =50000+Ten;intA[MAXN];intN, K;intcmpintAintb) { returnA >b;}BOOLIsfound (intx) {intL =0, R = N1, Mid; while(L <=r) {Mid= (l+r) >>1; if(A[mid] >x) R= Mid-1; Else if(A[mid] <x) L= Mid +1; Else return 1; } return 0;}intMain () {//freopen ("1.txt", "R", stdin);scanf"%d%d", &k, &N); for(inti =0; i < N; i++) {scanf ("%d", &A[i]); } sort (A, a+N); intFlag =0; for(inti =0; i < N; i++) { if(Isfound (K-a[i]) && a[i]<k/2) {flag=1; printf ("%d%d\n", A[i], K-A[i]); } } if(!flag) printf ("No solution\n"); return 0;}//otherintFlag =0;intj = N1; for(inti =0; I < J; i++) { while(I < J && A[i]+a[j]>k) j--;//Narrow the range if(A[i]+a[j] = = k && I <j) {printf ("%d%d\n", A[i], a[j]); Flag=1; }}if(!flag) printf ("No solution\n");
[Number pairs in 51nod]1001 array and equal to K