首页 > 其他 > 详细

UVA 10487 Closest Sums(二分)

时间:2015-02-12 09:21:48      阅读:226      评论:0      收藏:0      [点我收藏+]

                                       UVA 10487 Closest Sums



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<n<=1000), which indicates, how many numbers are in the set of integer. Next n lines contain n numbers. Of course there is only one number in a single line. The next line contains a positive integer m giving the number of queries, 0 < m < 25. The next m lines contain an integer of the query, one per line.

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.

Sample input

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 

Sample output

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<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
long long num[1005], ans[1005], sum[1000005];
int main() {
	int Case = 1;
	int n, m;
	while (scanf("%d", &n), n) {
		for (int i = 0; i < n; i++) {
			scanf("%lld", &num[i]);
		}
		scanf("%d", &m);
		for (int i = 0; i < m; i++) {
			scanf("%lld", &ans[i]);
		}
		int cnt = 0;
		for (int i = 0; i < n; i++) {
			for (int j = i + 1; j < n; j++) {
				sum[cnt++] = num[i] + num[j];
			}
		}
		sort(sum, sum + cnt);
		printf("Case %d:\n", Case++);
		int Ans;
		for (int i = 0; i < m; i++) {
			int l = 0, r = cnt - 1;
			long long Ans = 0, mid = (l + r) / 2, min = 999999999;
			if (sum[mid] == ans[i]) {
				Ans = ans[i];
			}
			else if (sum[mid] < ans[i]) {
				while (mid <= r) {
					if (min > abs(ans[i] - sum[mid])) {
						min = abs(ans[i] - sum[mid]);
						Ans = sum[mid];
					}
					mid++;
				}
			}
			else {
				while (mid >= l) {
					if (min > abs(sum[mid] - ans[i])) {
						min = abs(sum[mid] - ans[i]);
						Ans = sum[mid];
					}
					mid--;
				}
			}
			printf("Closest sum to %lld is %lld.\n", ans[i], Ans);
		}
	}
	return 0;
}




UVA 10487 Closest Sums(二分)

原文:http://blog.csdn.net/llx523113241/article/details/43741275

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!