题目描述
给定一个由n个整数组成的数组a,其中n为奇数。
你以对其进行以下操作:
■选择数组中的一个元素(例如a),将其增加1(即,将其替换为ai+1)。
你最多可以进行k次操作,并希望该数组的中位数能够尽可能大。
奇数长度的数组的中位数是数组以非降序排序后的中间元素。
例如,数组[1,5,2,3,5]的中位数为3。
输入格式
第一行包含两个整数n和k。
第二行包含n个整数a1,a2,.an。
输出格式
输出一个整数,表示通过操作可能得到的最大中位数。
#include <iostream>
#include <vector>
#include <unordered_set>
#include <cmath>
using namespace std;
struct Point {
int x, y;
Point(int x, int y) : x(x), y(y) {}
};
double getSlope(const Point& a, const Point& b) {
if (a.x == b.x) return numeric_limits<double>::infinity(); // 垂直线
return static_cast<double>(b.y - a.y) / (b.x - a.x);
}
int minLaserShots(int n, int xo, int yo, const vector<Point>& mice) {
unordered_set<double> slopes; // 存储不同斜率的集合
for (const auto& mouse : mice) {
double slope = getSlope(Point(xo, yo), mouse);
if (!isnan(slope) && !isinf(slope)) { // 排除无效和垂直线的斜率
slopes.insert(fabs(slope)); // 插入斜率的绝对值
}
}
// 如果存在垂直线(即所有老鼠的x坐标与激光枪相同),则额外需要一次发射
bool hasVerticalLine = false;
for (const auto& mouse : mice) {
if (mouse.x == xo) {
hasVerticalLine = true;
break;
}
}
return slopes.size() + (hasVerticalLine ? 1 : 0);
}
int main() {
int n, xo, yo;
cin >> n >> xo >> yo;
vector<Point> mice(n);
for (int i = 0; i < n; ++i) {
cin >> mice[i].x >> mice[i].y;
}
cout << minLaserShots(n, xo, yo, mice) << endl;
return 0;
}
本文讨论通过最少操作改变数组元素以最大化奇数数组的中位数,用C++实现激光射击策略。
1036

被折叠的 条评论
为什么被折叠?



