CCF-202009-1 Java解析
原题链接
http://118.190.20.162/view.page?gpid=T113
题目内容
题目背景
2020 年 6 月 8 日,国务院联防联控机制发布《关于加快推进新冠病毒核酸检测的实施意见》,提出对“密切接触者”等八类重点人群“应检尽检”,其他人群“愿检尽检”。
问题描述
某市设有n个核酸检测点,编号从1到n,其中i号检测点的位置可以表示为一个平面整数坐标(xi,yi)。
为方便预约核酸检测,请根据市民所在位置(X,Y),查询距其最近的三个检测点。
多个检测点距离相同时,编号较小的视为更近。
输入格式
输入共 n+1行。
第一行包含用空格分隔的三个整数n、X 和Y,表示检测点总数和市民所在位置。
第二行到第n+1行依次输入n个检测点的坐标。第i+1行(1<=i<=n)包含用空格分隔的两个整数xi和yi,表示i号检测点所在位置。
输出格式
输出共三行,按距离从近到远,依次输出距离该市民最近的三个检测点编号。
样例输入1
3 2 2
2 2
2 3
2 4
样例输出1
1
2
3
样例输入2
5 0 1
-1 0
0 0
1 0
0 2
-1 2
样例输出2
2
4
1
样例2解释
评测用例规模与约定
全部的测试点满足,3<=n<=200,所有坐标均为整数且绝对值不超过1000 。
提示
市民到第 i号检测点的距离
可由如下公式算出:
代码模块
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int X = scanner.nextInt();
int Y = scanner.nextInt();
//注意此处建议使用二元数组,[i][0]表示横坐标,[i][1]表示纵坐标,[i][2]表示下标
int[][] posArr = new int[n][3];
for (int i = 0; i < n; i++){
posArr[i][0] = scanner.nextInt();
posArr[i][1] = scanner.nextInt();
posArr[i][2] = i + 1;
}
//排序算法
sort(posArr, X, Y);
for (int i = 0; i < 3; i++) {
System.out.println(posArr[i][2]);
}
//注意关闭输入
scanner.close();
}
//排序算法,主要注意Arrays.sort算法,下面有解释
private static void sort(int[][] arr, int x, int y){
Arrays.sort(arr, ((o1, o2) ->{
int dis1 = discount(x, y, o1[0], o1[1]);
int dis2 = discount(x, y, o2[0], o2[1]);
//注意输出格式,比较dis1和dis2是否相等,相等则返回下标从小到大,如果不等则返回两个距离从小到大
return dis1 == dis2 ? o1[2]-o2[2] : dis1 - dis2;
}));
}
private static int discount(int x, int y, int posX, int posY) {
return (posX - x) * (posX - x) + (posY - y) * (posY - y);
}
}
Arrays.sort关于Comparator的用法
public class Test {
public static void main(String[] args) {
Integer[] arr = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5};
Arrays.sort(arr, (o1,o2)->{return o2-o1;});
for(int x:arr){
System.out.print(x); //print: 9876543210
}
}
}