Sum
Time Limit: 9000 MS Memory Limit: 65536 K
Sum
Mr. Jojer is given n numbers and an extra integer x, he wants to know whether there are two numbers whose sum is x.
Input
The input file contains several test cases. The first line of each test case contains two integers, n(<=1000001) and x. From the next line of each test case, there are n numbers.
Output
Each test case corresponds to a line in the output, which is either "YES" if there exists an answer or "NO" if not.
Sample Input
3 3
1 2 3
2 3
1 3
Sample Output
YES
NO
#include<iostream>
#include<algorithm>
using namespace std;
int a[1001],n,goal;
int main()
{
int i,j;
while(scanf("%d%d",&n,&goal)==2)
{
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
sort(a,a+n);
if(a[n-4]+a[n-1]+a[n-2]+a[n-3]<goal) {printf("NO/n");continue;}
int flag=0;
for(i=0;i+3<n;i++)
{
if(a[i]+a[i+1]+a[i+2]+a[i+3]>goal) break;
for(j=i+1;j<n;j++)
{
int low=j+1,high=n-1,t;
while (low<high)
{
t=a[low]+a[high]+a[i]+a[j];
if (t==goal) {flag=1;break;}
else if (t<goal) low++;
else high--;
}
if(flag) break;
}
if(flag) break;
}
if(flag) printf("YES/n");
else printf("NO/n");
}
return 0;
}