程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> UVA 10487 - Closest Sums

UVA 10487 - Closest Sums

編輯:C++入門知識

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<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 mlines 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

312173334315130312331233

12334560Sample 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<math.h>
#include<algorithm>
using namespace std;
int a[1005],s[1000005],q[30];
int main()
{
	int i,j,p,n,m,k,cas=0;
	while(~scanf("%d",&n)&&n)
	{
		for(i=0;i<n;i++)
			scanf("%d",&a[i]);
		for(i=0,k=0;i<n-1;i++)
			for(j=i+1;j<n;j++)
				s[k++]=a[i]+a[j];
		sort(s,s+k);
		scanf("%d",&m);
		for(i=0;i<m;i++)
			scanf("%d",&q[i]);
		printf("Case %d:\n",++cas);
		for(j=0;j<m;j++)
		{
			if(q[j]<=s[0])
				p=s[0];
			else if(q[j]>=s[k-1])
				p=s[k-1];
			else
			{
				for(i=0;i<k;i++)
				{
					if(s[i]<q[j])
					     continue;
					else
					{
						p=abs(s[i]-q[j])<abs(s[i-1]-q[j])?s[i]:s[i-1];
						break;
					}
				}
			}
			printf("Closest sum to %d is %d.\n",q[j],p);
		}
	}
	return 0;
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved