10487 - Closest Sums
Moderator: Board moderators
-
- Experienced poster
- Posts: 193
- Joined: Thu Sep 19, 2002 6:39 am
- Location: Indonesia
- Contact:
Let's say you have these numbers in the input: 1, 1, and 3 ... (notice there are two ones there) ...
The possible sum is:
1+3 -> 4
Notice that 1+1 -> 2 cannot be used since both numbers are the same. The problem description requires the numbers to be distinct.
So, for input
The output should be:
-turuthok-
The possible sum is:
1+3 -> 4
Notice that 1+1 -> 2 cannot be used since both numbers are the same. The problem description requires the numbers to be distinct.
So, for input
Code: Select all
3
1
1
3
1
2
0
Code: Select all
Case 1:
Closest sum to 2 is 4.
The fear of the LORD is the beginning of knowledge (Proverbs 1:7).
I can't still solve the problem.
it gives me WA. btu donno why.
Would you please give some critical cases for my program?
here it is.
simple, first sort, then find distinct numbers, then, just check for the closest. But, why WA??
it gives me WA. btu donno why.
Would you please give some critical cases for my program?
here it is.
Code: Select all
#include<stdio.h>
#include<math.h>
#define N 1005
main()
{
freopen("in.txt","r",stdin);
long int cas=1,n,i,j,h,m,z,a[N],l,dif,now,pre,b[N];
while(scanf("%ld",&n)!=EOF && n)
{
printf("Case %ld:\n",cas);cas++;
for(i=0;i<n;i++) scanf("%ld",&b[i]);
for(i=0;i<n;i++)
{
h=i;
for(j=i+1;j<n;j++) if(b[j]<b[h]) h=j;
j=b[h];b[h]=b[i];b[i]=j;
}
h=1;a[0]=b[0];
for(i=1;i<n;i++) if(b[i]!=b[i-1]) a[h++]=b[i];n=h;
scanf("%ld",&m);
for(z=0;z<m;z++)
{
scanf("%ld",&l);
dif=pre=abs(a[0]+a[1]-l),now=a[0]+a[1];
for(i=0;i<n;i++)
{
for(j=i+1;j<n && abs(a[i]+a[j]-l)<=pre;j++) pre=abs(a[i]+a[j]-l);
if(pre<dif) dif=pre,now=a[i]+a[j-1];
}
printf("Closest sum to %ld is %ld.\n",l,now);
}
}
return 0;
}
"Everything should be made simple, but not always simpler"
Consider this input:
your program gives:7
13
19
29
86
73
11
53
4
87
92
43
120
0
and my AC program gives something else:Case 1:
Closest sum to 87 is 84.
Closest sum to 92 is 97.
Closest sum to 43 is 40.
Closest sum to 120 is 126.
Case 1:
Closest sum to 87 is 86.
Closest sum to 92 is 92.
Closest sum to 43 is 42.
Closest sum to 120 is 115.