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 <stdio.h>
# include <malloc.h>
int main()
{int b,i,j,n,x;
int *a=NULL;
//freopen("in.txt","r",stdin);
a=(int*)malloc(1000001*sizeof(int));
while(scanf("%d %d",&n,&x)==2)
{
b=0;
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1&&!b;i++)
{if(a[i]>x) continue;
for(j=i+1;j<n&&!b;j++)
if(a[i]==x-a[j]) b=1;
}
if (b==1)
printf("YES/n");
else
printf("NO/n");
}
free(a);
return 0;
}
外循环用X,还超时
# include <stdio.h>
# include <malloc.h>
int main()
{int cz,b1,b2,i,j,n,x;
int *a=NULL;
//freopen("in.txt","r",stdin);
a=(int*)malloc(1000001*sizeof(int));
while(scanf("%d %d",&n,&x)==2)
{
cz=0;
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=1;i<=x/2;i++)
{b1=0;b2=0;
for(j=0;j<n;j++)
{if(b1&&x-i==a[j]) b2=1;
if(i==a[j]) b1=1;
}
if(b1&&b2) cz=1;
}
if (cz==1)
printf("YES/n");
else
printf("NO/n");
}
free(a);
return 0;
}
利用数组地址做,Runtime erroe
# include "stdio.h"
int main()
{int m,x;
long i,n;
bool a[65535];
bool b;
while(scanf("%ld%d",&n,&x)==2)
{
b=false;
for(i=0;i<65535;i++)
a[i]=false;
for(i=0;i<n;i++)
{scanf("%d",&m);
if (x>m)
if(a[x-m]==true)
b=true;
else if (m<=65535) a[m]=true;
}
if (b==true)
printf("YES/n");
else
printf("NO/n");
}
return 0;
}
自以为都对,却都不对
#include <map>
#include <string>
#include <stdio.h>
# include <malloc.h>
using namespace std;
int main()
int b,i,j,n,x,key;
int *a=NULL;
multimap<int,int,less<int> >mulmap;
multimap<int,int,less<int> >::iterator p;
//初始化多重映射mulmap:
typedef multimap<int,int,less<int> >::value_type vt;
typedef int s;
a=(int *)malloc(1000001*sizeof(int));
while(scanf("%d%d",&n,&x)==2)
{
b=0;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
mulmap.insert(vt(s(a[i]),s(i)));
}
for(i=0;i<n&&!b;i++)
{
if(a[i]+a[i]==x)
{
int count=0;
for(j=0;j<n;j++)
if(a[j]==x/2) count++;
if(count>1) b=1;
} else
if(mulmap.find(s(x-a[i]))!=mulmap.end())
b=1;
}
if (b) printf("YES/n");
else printf("NO/n");
mulmap.clear();
}
return 0;