1001 Number pair base time limit in array and equal to K: 1 seconds Space limit: 131072 KB Score: 5 Difficulty: 1-level algorithm topic collection focus on giving an integer k and an unordered array a,a the elements are n distinct integers, finding all and equal K pairs 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
"Analysis": The violence will be tle, two points ~ can be a double pointer/stl/binary function (http://www.cnblogs.com/wuzetiandaren/p/4259199.html) similar.
"Code":
#include <bits/stdc++.h>using namespacestd;Const intMAXN =50000+Ten;intN,k,l,r;intA[MAXN];intMain () {//freopen ("In.txt", "R", stdin); while(cin>>k>>N) {intflag=1; for(intI=0; i<n;i++) {cin>>A[i]; } sort (A,a+N); intI=0, j=n-1; while(i<j) {if(a[i]+a[j]==k) {L=i; R=J; Flag=0; printf ("%d%d\n", A[l],a[r]); } if(a[i]+a[j]>k) {J--; } Else{i++; } } if(flag) printf ("No solution\n"); } return 0;}
Double pointer
#include <bits/stdc++.h>using namespacestd;Const intMAXN =50000+Ten;intN,k,t,l,r;intA[MAXN];intMain () {//freopen ("In.txt", "R", stdin); while(cin>>k>>N) {intflag=1; for(intI=0; i<n;i++) {cin>>A[i]; } sort (A,a+N); for(intI=0; i<n;i++) {T=lower_bound (A,a+n,k-a[i])-A; if(a[t]==k-a[i]&&t>i) {printf ("%d%d\n", a[i],k-A[i]); Flag=0; } } if(flag) printf ("No solution\n"); } return 0;}
STL
51nod 1001 Number Pairs "binary Find/Sort" in array and equal to K