Defibrillators
问题地址:Defibrillators。
这道题难的地方不是在于代码实现有多难,而是能不能审题审清楚了:
-
计算公式都算对了吗?
x = ( l o n g i t u d e B − l o n g i t u d e A ) × cos ( l a t i t u d e A + l a t i t u d e B 2 ) x = (longitudeB - longitudeA) \times \cos(\frac{latitudeA + latitudeB}{2}) x=(longitudeB−longitudeA)×cos(2latitudeA+latitudeB)
y = l a t i t u d e B − l a t i t u d e A y = latitudeB - latitudeA y=latitudeB−latitudeA
d = x 2 + y 2 × 6371 d = \sqrt{x^{2} + y^{2}} \times 6371 d=x2+y2×6371
-
题目看清楚了吗?
Note: In this formula, the latitudes and longitudes are expressed in radians. 6371 corresponds to the radius of the earth in km.
对,这句话的意思是要把 degree 转成 radian……我第二步就死在这里还以为自己的计算公式写错了。
-
它给的值,转换了吗?
原题中的一个 example input 如下:
1;Maison de la Prevention Sante;6 rue Maguelone 340000 Montpellier;;3,87952263361082;43,6071285339217
注意第 4 位和第 5 位的格式:
3,87952263361082 和 43,6071285339217
所以需要将
,
转换成.
,我第一步就死在了这里,还在想为什么所有的距离都是 0……
卡了几个小时都是卡在审题没审清,我还在想一个 easy 的题目为什么会这么难。一旦看清楚题目了之后这个题就很简单了,解法:
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
// remove parseInt for LON and LAT
const LON = readline();
const LAT = readline();
const N = parseInt(readline());
/**
* remove , and convert string to float
* @param {string} degree - The degree in string format, can have invalid separator
* @return {float} parsed degree
*/
const getFloatVal = (degree) => {
const parsedDegree = degree.split(",").join(".");
return parseFloat(parsedDegree);
};
/**
* convert degree to radian
* @param {float} degree - the degree value
* @return {float} in radian value
*/
degreetoRadian = (degree) => {
return (getFloatVal(degree) * Math.PI) / 180;
};
/**
* convert longitutes and latitudes to radian values
* @param {string} lonA
* @param {string} lonB
* @param {string} latA
* @param {string} latB
* @return {Array} - array of 4 values in radian
*/
convertToRadian = (lonA, lonB, latA, latB) => {
return [
degreetoRadian(lonA),
degreetoRadian(lonB),
degreetoRadian(latA),
degreetoRadian(latB),
];
};
/**
* get distance between location
* @param {string} lonA
* @param {string} lonB
* @param {string} latA
* @param {string} latB
* @return {float} - distance between 2 locations
*/
const getDistance = (lonA, lonB, latA, latB) => {
const [lonARan, longbRan, latARan, labBRan] = convertToRadian(
lonA,
lonB,
latA,
latB
);
const x = (longbRan - lonARan) * Math.cos((latARan + labBRan) / 2);
const y = labBRan - latARan;
return Math.sqrt(x * x + y * y) * 6371;
};
let minDistance = Number.MAX_VALUE;
let closetLoc = "";
for (let i = 0; i < N; i++) {
const DEFIB = readline();
const locDetails = DEFIB.split(";");
const distance = getDistance(LON, locDetails[4], LAT, locDetails[5]);
if (distance < minDistance) {
minDistance = distance;
closetLoc = locDetails[1];
}
}
// Write an answer using console.log()
// To debug: console.error('Debug messages...');
console.log(closetLoc);