題目連結
題意:
一條數線(很長的道路)上,每組測資會有若干個點(商店),
選定任意位置停車,要輸出走訪各點並回到停車處的最小距離。
解法:
不管在哪停車,走訪各點並回到停車處最近的方式是,
分別往返停車處的左與右邊最遠的點(途中會經過其他點,也算走訪)。
因此,題目可以看成計算兩個相隔最遠的商店距離
也就是求這些點當中,座標最大與最小之差的兩倍(來回)
程式(Java):
題意:
一條數線(很長的道路)上,每組測資會有若干個點(商店),
選定任意位置停車,要輸出走訪各點並回到停車處的最小距離。
解法:
不管在哪停車,走訪各點並回到停車處最近的方式是,
分別往返停車處的左與右邊最遠的點(途中會經過其他點,也算走訪)。
因此,題目可以看成計算兩個相隔最遠的商店距離
也就是求這些點當中,座標最大與最小之差的兩倍(來回)
程式(Java):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Main { | |
public static void main(String arg[]) { | |
Scanner sc = new Scanner(System.in); | |
int t = sc.nextInt(); | |
while (t-- > 0) { | |
int n = sc.nextInt(); | |
int max = -1, min = 100; | |
while (n-- > 0) { | |
int x = sc.nextInt(); | |
if (x > max) | |
max = x; | |
if (x < min) | |
min = x; | |
} | |
System.out.println("" + 2*(max - min)); | |
} | |
} | |
} |
留言
張貼留言