#P3074. 预订酒店(100分)
-
1000ms
Tried: 94
Accepted: 48
Difficulty: 2
所属公司 :
华为od
预订酒店(100分)
自定义排序
有优先级,比如sort函数sort(a+1,a+n+1);这样写法的cmp等同于
int cmp(int x,int y){
return x<y;
}
按题目要求我们可以把第一abs(x-k)<abs(y-k),第二也就是差值相等优先选择价格低一点的也就是x<y,具体实现看代码,题目要求按从小输出,自定义排序完之后,在对前k个进行sort即可
代码如下
cpp
#include <bits/stdc++.h>
using namespace std;
int numHotels, targetPrice, numSelect; // 定义输入的酒店数量、心理价位和需要选择的酒店数量
int hotelPrices[10000]; // 酒店价格数组
// 自定义比较函数,用于按照距离心理价位的差值进行排序
int comparePrices(int price1, int price2) {
// 比较两者与心理价位的差值
if(abs(price1 - targetPrice) != abs(price2 - targetPrice)) {
return abs(price1 - targetPrice) < abs(price2 - targetPrice); // 优先选择差值较小的
}
return price1 < price2; // 如果差值相同,则选择价格较低的
}
int main() {
// 读取输入
cin >> numHotels >> numSelect >> targetPrice;
for(int i = 1; i <= numHotels; i++) {
cin >> hotelPrices[i]; // 输入酒店价格
}
// 按照自定义比较函数对酒店价格进行排序
sort(hotelPrices + 1, hotelPrices + numHotels + 1, comparePrices);
// 对前 numSelect 个酒店按价格从低到高排序
sort(hotelPrices + 1, hotelPrices + numSelect + 1);
// 输出前 numSelect 个酒店的价格
for(int i = 1; i <= numSelect; i++) {
cout << hotelPrices[i] << ' ';
}
cout << '\n';
return 0;
}
python
n, k, x = map(int, input().split())
hotel_prices = list(map(int, input().split()))
hotel_prices.sort(key=lambda price: (abs(price - x), price))
selected_prices = sorted(hotel_prices[:k])
print(" ".join(map(str, selected_prices)))
java
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int k = scanner.nextInt();
int x = scanner.nextInt();
Integer[] hotelPrices = new Integer[n];
for (int i = 0; i < n; i++) {
hotelPrices[i] = scanner.nextInt();
}
Arrays.sort(hotelPrices, (price1, price2) -> {
int diff1 = Math.abs(price1 - x);
int diff2 = Math.abs(price2 - x);
if (diff1 != diff2) {
return diff1 - diff2;
} else {
return price1 - price2;
}
});
Integer[] selectedPrices = Arrays.copyOfRange(hotelPrices, 0, k);
Arrays.sort(selectedPrices);
for (int price : selectedPrices) {
System.out.print(price + " ");
}
}
}
题目内容
放暑假了,小红决定到某旅游景点游玩,他在网上搜索到了各种价位的酒店(长度为 n 的数组 A),他的心理价位是 x 元,
请帮他筛选出 k 个最接近 x 元的酒店(n≥k>0),并由低到高打印酒店的价格。
备注
- 酒店价格数组 A 和小红的心理价位 x 均为整型数据(0<n,k,x<10000)
- 优先选择价格最接近心理价位的酒店,若两家酒店距离心理价位差价相同,则选择价格较低的酒店。(比如 100 元和 300 元距离心理价位 200 元同样接近,此时选择 100 元)
- 酒店价格可能相同重复
输入描述
第一行:n,k,x
第二行:A[0]A[1]A[2]…A[n−1]
输出描述
从低到高打印筛选出的酒店价格
样例1
输入
10 5 6
1 2 3 4 5 6 7 8 9 10
输出
4 5 6 7 8
说明
数组长度 n=10,筛选个数 k=5,目标价位 x=6
样例2
输入
10 4 6
10 9 8 7 6 5 4 3 2 1
输出
4 5 6 7
说明
数组长度 n=10,筛选个数 k=4,目标价位 x=6
当4和8时距离 x 相同时,优先选择价格低的4
样例3
输入
6 3 1000
30 30 200 500 70 300
输出
200 300 500
说明