UVA 10487 Closest Sums (二分查找)

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

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个数字。在给定m个数字。在m个数字中。找出最接近该数字的 前n的数字中两个数字之和。。

思路:一开始直接暴力。。居然过了。估计数据水不然会超。正确的做法应该是二分查找。(比如m很大的话,每找一个数字都要重新算n *(n-1)/ 2次和,这种操作要进行m次。而用二分的话只需要1次。)。先把每两个数字之和存起来。然后根据输入的数字。用二分查找找到一个最接近的数。。还是要注意细节的地方。因为这个wa了几次。

代码:

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <algorithm>
using namespace std;

int n, m, i, j, sb;
int num[1005];
int sum[500005];

int main() {
	int t = 1;
	while (~scanf("%d", &n) && n) {
		int sumn = 0;
		for (i = 0; i < n; i ++) {
			scanf("%d", &num[i]);
		}
		for (i = 0; i < n; i ++)
			for (j = i + 1; j < n; j ++) {
				if (num[i] != num[j])
					sum[sumn ++] = num[i] + num[j];
			}
			sort(sum, sum + sumn);
			scanf("%d", &m);
			printf("Case %d:\n", t ++);
			while (m --) {
				scanf("%d", &sb);
				int sbb;
				if (sb >= sum[sumn - 1]) {sbb = sumn - 1;}
				else if (sb <= sum[0]) {sbb = 0;}
				else {
					int star = 0, end = sumn - 1;
					while (end != star) {
						sbb = (star + end) / 2;
						if (sum[sbb] < sb) {
							if (sbb == star) break;
							star = sbb;
						}
						else if (sum[sbb] > sb) {
							if (sbb == end) break;
							end = sbb;
						}
						else 
							break;
					}
				}
				if (abs(sum[sbb - 1] - sb) < abs(sb - sum[sbb]) && sbb != 0)
					sbb --;
				if (abs(sum[sbb + 1] - sb) < abs(sb - sum[sbb]) && sbb != sumn - 1)
					sbb ++;
				printf("Closest sum to %d is %d.\n", sb, sum[sbb]);
			}
	}
	return 0;
}

附上一开始暴力水过的代码- - 代码上是简单了不少。。而且居然跑得更快。。无解。估计是n大的数据里面。m都很小甚至为1吧。。。哎

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <algorithm>
using namespace std;

int n, m, i, j, sb, sbb;
int num[1005];
int minn;
int sum;

int main() {
	int t = 1;
	while (~scanf("%d", &n) && n) {
		int sumn = 0;
		for (i = 0; i < n; i ++) {
			scanf("%d", &num[i]);
		}
		scanf("%d", &m);
		printf("Case %d:\n", t ++);
		while (m --) {
			scanf("%d", &sb);
			int minn = 999999999;
			for (i = 0; i < n; i ++)
				for (j = i + 1; j < n ; j ++) {
					sum = num[i] + num[j];
					if (abs(sum - sb) < minn) {
						minn = abs(sum - sb);
						sbb = sum;
					}
				}			
				printf("Closest sum to %d is %d.\n", sb, sbb);
		}
	}
	return 0;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
二分K均值是一种基于K均值算法的改进方法,用于图像分割时可以得到更好的结果。 实现步骤如下: 1. 将图像转化为一维数组。 2. 设定初始的K个聚类中心(可以随机选择或使用其他方法),计算每个像素点与聚类中心的距离,并将其归入距离最近的类别中。 3. 计算每个类别的平均值作为新的聚类中心。 4. 重复步骤2和步骤3,直到聚类中心不再发生变化或达到设定的迭代次数。 5. 对于二分K均值,将所有样本归入一个初始类别中,然后将其分成两个子类别。对每一个子类别重复1-4步骤,直到达到设定的最大类别数或某些停止条件。 6. 最终将每个像素点归入距离最近的聚类中心所在的类别中,即可得到图像分割结果。 下面是Python代码实现: ```python import numpy as np from PIL import Image def binary_kmeans(image_path, k_max=10, max_iter=20): # Load image image = Image.open(image_path) pixels = np.array(image).reshape(-1, 3) # Initialize with one cluster clusters = [(0, pixels)] # Binary K-means loop while len(clusters) < k_max: # Choose the cluster with maximum SSE sse_list = [np.sum((cluster[1] - np.mean(cluster[1], axis=0)) ** 2) for cluster in clusters] max_sse_idx = np.argmax(sse_list) max_sse_cluster = clusters[max_sse_idx] # Split the cluster into two sub-clusters kmeans = KMeans(n_clusters=2, max_iter=max_iter).fit(max_sse_cluster[1]) sub_clusters = [(max_sse_cluster[0] * 2 + i, max_sse_cluster[1][kmeans.labels_ == i]) for i in range(2)] # Replace the original cluster with the sub-clusters clusters = clusters[:max_sse_idx] + sub_clusters + clusters[max_sse_idx + 1:] # Assign each pixel to the closest cluster labels = np.zeros(len(pixels), dtype=int) for cluster in clusters: labels[np.argmin(np.sum((pixels - np.mean(cluster[1], axis=0)) ** 2, axis=1))] = cluster[0] # Reshape the labels back to an image return labels.reshape(image.size[1], image.size[0]) ``` 其中,`image_path`为需要分割的图像路径,`k_max`为最大聚类数,`max_iter`为每个子类别的最大迭代次数。该函数返回每个像素点所属的类别标签,可以使用不同的颜色来可视化分割结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值