Title Address: http://acm.fafu.edu.cn/problem.php?id=1048
Description:
Given N positive integers and a positive integer P, you are asked to find two numbers a,b makes A + b = p;
Input:
The first line is two digits n,p (n<=10^5;p,n integer <2^32); Second Line N a number . (with multiple sets of test data)
Output:
If you can find these two digital outputs Yes, otherwise output No.
Sample Input:
3 3
1 2 3
4 2
1 3 2 1
1 5
5
Sample Output:
Yes
Yes
No
The question is: Can you find two number ain the given n number, andb add equals p
First of all, the topic said is a positive integer, so no negative number is not 0; So we can delete the input of the data greater than or equal to p , thus reducing the number of subsequent searches, Then we put these numbers from small to large (of course, from large to small), starting from the beginning and the tail to find the two numbers. Suppose we put a number in the num[20] array, head represents the head, andtail represents the tail (that is, the last element of the array is subscript).
At first head = 0,tail = +;
(1) if Num[head] + num[tail] is greater than P, indicating that the number of the tail is too large, should take a smaller value, so tail--;
(2) if Num[head] + num[tail] is less than p, the figure of the head is too small, should take a larger value, so head++;
(3) if Num[head] + num[tail] equals p, the description is found.
Here is the source code:
#include <cstdio>#include<cstring>#include<algorithm>using namespacestd;Long Longp;Long Longnum[100005];intMainvoid){ intN,i=0, j,flag=0; memset (num,0,sizeof(num)); while(SCANF ("%d%lld", &n,&p) = =2) { while(n--) {scanf ("%lld",&Num[i]); if(Num[i] >= p)Continue;//If the number entered is greater than P, discardi++; } N= i;//N is the number of digits remaining after dropping discardedSort (num,num+N); for(i=0, j=n-1; i<J;) { if(Num[i]+num[j] > P) j--;//greater than p indicates that the rightmost is too large, take a little bit, move left Else if(Num[i]+num[j] < p) i++;//less than P description The leftmost is too small, take a little bigger, move right Else{flag =1; Break;}//equal, found the } if(flag) printf ("yes\n"); Elseprintf"no\n"); I= Flag =0; memset (num,0,sizeof(num)); } return 0;}
View Code
Simple look-up problems