Problem D
Closest Sums
Input: standard input
Output: standard output
Time Limit: 3 seconds
Given is a set of integers and then a sequence of queries. A query gives you a number and asks to find a sum of two distinct numbers from the set, which is closest to the query number.
Input
Input contains multiple cases.
Each case starts with an integer n (1
Input is terminated by a case whose n=0. Surely, this case needs no processing.
Output
Output should be organized as in the sample below. For each query output one line giving the query value and the closest sum in the format as in the sample. Inputs will be such that no ties will occur.
5
3
12
17
33
34
3
1
51
30
3
1
2
3
3
1
2
3
3
1
2
3
3
4
5
6
0
Case 1:
Closest sum to 1 is 15.
Closest sum to 51 is 51.
Closest sum to 30 is 29.
Case 2:
Closest sum to 1 is 3.
Closest sum to 2 is 3.
Closest sum to 3 is 3.
Case 3:
Closest sum to 4 is 4.
Closest sum to 5 is 5.
Closest sum to 6 is 5.
题意:
找到与其最接近的和的值,
之前做的时候一直给忘记考虑不在和范围内的值;
#include
#include
#include
#include
#include
#define N 1000
using namespace std;
int a[N];
int b[N];
int c[N*N];
int k;
int n, m;
void solve() {
k = 0;
for (int i = 0; i < n; i++)
for (int j = i+1; j < n; j++) {
c[k++] = a[i] + a[j];
}
// c[k++] = 0x3f3f3f3f;
// c[k++] = -0x3f3f3f3f;
sort(c,c+k);
}
void fun(int key) {
for (int i = 0; i < k - 1; i++) {
if (key >= c[i] && key <= c[i+1]) {
if ((key - c[i]) < (c[i+1] - key)) {
printf("Closest sum to %d is %d.\n",key,c[i]);
return ;
}
else {
printf("Closest sum to %d is %d.\n",key,c[i+1]);
return ;
}
}
}
if (key < c[0])
printf("Closest sum to %d is %d.\n",key,c[0]);
else if (key > c[k-1])
printf("Closest sum to %d is %d.\n",key,c[k-1]);
}
int main () {
int kase = 0;
int t;
int b;
while (scanf("%d",&n) != EOF) {
if (n == 0) break;
printf("Case %d:\n",++kase);
memset(a,0,sizeof(a));
memset(c,0,sizeof(c));
for (int i = 0; i < n; i++)
scanf("%d",&a[i]);
solve();
scanf("%d",&m);
for (int i = 0; i < m; i++) {
cin >> b;
fun(b);
}
}
return 0;
}
还有一种方法:
#include
#include
#include
#include
#include
#define N 1000
using namespace std;
int a[N];
int b[N];
int c[N*N];
int k;
int n, m;
void solve() {
k = 0;
for (int i = 0; i < n; i++)
for (int j = i+1; j < n; j++) {
c[k++] = a[i] + a[j];
}
c[k++] = 0x3f3f3f3f; // 取到最大值
c[k++] = -0x3f3f3f3f; // 取到最小值,这样就能保证在其范围之内;
sort(c,c+k);
}
void fun(int key) {
for (int i = 0; i < k - 1; i++) {
if (key >= c[i] && key <= c[i+1]) {
if ((key - c[i]) < (c[i+1] - key)) {
printf("Closest sum to %d is %d.\n",key,c[i]);
}
else {
printf("Closest sum to %d is %d.\n",key,c[i+1]);
}
}
}
}
int main () {
int kase = 0;
int t;
int b;
while (scanf("%d",&n) != EOF) {
if (n == 0) break;
printf("Case %d:\n",++kase);
memset(a,0,sizeof(a));
memset(c,0,sizeof(c));
for (int i = 0; i < n; i++)
scanf("%d",&a[i]);
solve();
scanf("%d",&m);
for (int i = 0; i < m; i++) {
cin >> b;
fun(b);
}
}
return 0;
}