1. 程式人生 > >PAT 1046 Shortest Distance (20 分)Java實現

PAT 1046 Shortest Distance (20 分)Java實現

題目連結:Shortest Distance

題意:

給你N個出口,出口是環狀的,告訴你出口之間的距離
最後給出任意兩個出口,求最短距離

思路:

這道題我一開始用遍歷的方法做,向前遍歷距離,向後遍歷距離
然後比較大小
這樣會超時,我們在輸入資料的時候就儲存好每個點到起始點距離
最後查詢只要O(1)的複雜度。。
但是Java還是會卡最後一個測試點。

程式碼:

package adv1046;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/** * @author zmj * @create 2018/11/22 */ public class Main { static int[] arr, dis; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] first = br.readLine().split(" "); int
N = Integer.parseInt(first[0]); arr = new int[N+1]; dis = new int[N+1]; int sum = 0; for (int i = 1; i <= N; i++) { arr[i] = Integer.parseInt(first[i]); sum += arr[i]; dis[i] = sum; } int M = Integer.parseInt(br.readLine
()); for (int i = 0; i < M; i++) { String[] line = br.readLine().split(" "); int s = Integer.parseInt(line[0]); int e = Integer.parseInt(line[1]); if (s > e) { int t = s; s = e; e = t; } int pre = dis[e-1] - dis[s-1]; int next = sum - dis[e-1] + dis[s-1]; System.out.println(Math.min(pre, next)); } } }

測試圖:

在這裡插入圖片描述