使用C++的CCF-CSP满分解决方案 202009-1 称检测点查询

本文介绍了一种使用贪心策略来解决最优距离选择问题的方法。通过输入一系列坐标点,该算法能够找出距离目标点最近的三个点,并返回这些点的位置编号。实现过程中采用了C++语言,利用了标准库中的I/O操作和数据结构处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

思路

大概想到两种,一种是优先队列,重构优先级,第二种是贪心,选到比原来小的就更新,方便起见我用的是第二种,代码如下:

满分代码实现(自解)

#include <map>
#include <set> 
#include <queue>
#include <iostream>
#include <algorithm>
using namespace std;

class Solution {
public:
	void solve();
}; 

void Solution::solve() {
	int n = -1;
	double X = -1, Y = -1;
	cin >> n >> X >> Y;
	double x = -1, y = -1;
	double distance = -1;
	int f = 1, s = 2, t = 3;
	double first = 0, second = 0, third = 0;
	cin >> x >> y;
	first = (X - x) * (X - x) + (Y - y) * (Y - y);
	cin >> x >> y;
	second = (X - x) * (X - x) + (Y - y) * (Y - y);
	if (second < first) {
		swap(f, s);
		swap(first, second);
	}
	cin >> x >> y;
	third = (X - x) * (X - x) + (Y - y) * (Y - y);
	if (third < first) {
		swap(s, t);
		swap(f, s);
		swap(third, second);
		swap(first, second);
	}
	else if (third < second) {
		swap(s, t);
		swap(third, second);
	}
	for (int i = 4; i <= n; i++) {
		cin >> x >> y;
		distance = (X - x) * (X - x) + (Y - y) * (Y - y);
		if (distance < first) {
			third = second;
			second = first;
			t = s;
			s = f;
			f = i;
			first = distance;
		}
		else if (distance < second) {
			third = second;
			t = s;
			s = i;
			second = distance;
		}
		else if (distance < third) {
			t = i;
			third = distance;
		}
	}
	cout << f << endl;
	cout << s << endl;
	cout << t;
}

int main() {
	// 提高cin,cout的速度
	ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	Solution s;
	s.solve();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值