Uva 10487 — Closest Sums
来源:互联网 发布:大学圈子 知乎 编辑:程序博客网 时间:2024/05/21 21:34
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.
题意:给出n个数 从任意两数之和中 找出与某个数最接近的数,
分析:存数,二分查找,第一次写二分 弱弱的
<pre name="code" class="cpp">#include<stdio.h>#include<algorithm>#include<iostream>using namespace std;int s[6000000];int find(int l,int r,int t)//二分查找{ if(r-l==1) return l; int m=l+(r-l)/2; if(s[m]<=t&&s[m+1]>=t) return m; if(s[m]<t) return find(m,r,t); if(s[m]>t) return find(l,m,t);}int main(){ int n,m,i,j,b; int a[1100]; int nn=0,r; while(scanf("%d",&n),n) { nn++;r=0; for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) s[r++]=a[i]+a[j];//将任意两数的和存到s数组中; sort(s,s+r); printf("Case %d:\n",nn); scanf("%d",&m); while(m--) { scanf("%d",&b); if(b<=s[0]) printf("Closest sum to %d is %d.\n",b,s[0]); else if(b>=s[r-1]) printf("Closest sum to %d is %d.\n",b,s[r-1]); else { int k=find(0,r-1,b); if(b-s[k]>(s[k+1]-b)) printf("Closest sum to %d is %d.\n",b,s[k+1]); else printf("Closest sum to %d is %d.\n",b,s[k]); } } }return 0;}
- Uva 10487 — Closest Sums
- UVa 10487 - Closest Sums
- UVa 10487 - Closest Sums
- uva 10487 - Closest Sums
- uva 10487 - Closest Sums
- UVa 10487 - Closest Sums
- UVa 10487 - Closest Sums
- UVa 10487 - Closest Sums
- uva 10487 - Closest Sums
- UVA 10487 - Closest Sums
- uva 10487 Closest Sums
- uva 10487 Closest Sums
- uva 10487 Closest Sums
- UVa 10487 - Closest Sums
- UVa 10487 - Closest Sums
- UVa-10487-Closest Sums
- UVA - 10487 Closest Sums
- uva-10487 - Closest Sums
- 桥接和网桥
- Android分屏显示LogCat
- 数据存储(二)--SAX引擎XML存储(附Demo)
- java内部类
- 笑玮基金—大型公益活动在京圆满举行
- Uva 10487 — Closest Sums
- SciPy-数值计算库
- DedeCms【挑错模块】错误类型的错误(BUG)
- 《Linux》天影linux系列笔记一——linux常用命令详解:grep
- 交换机
- 【第二章】制作自己第一个Phaser游戏--HTML5
- 黑马程序员----Java中的封装,继承和多态详解
- lib 中 make 失败后,source中make 结果 错误 怎么办
- 《Linux》天影linux系列笔记一——linux常用命令详解:ping