PAT 甲級 1046.Shortest Distance C++/Java

題目來源html

The task is really simple: given N exits on a highway which forms a simple cycle, you are supposed to tell the shortest distance between any pair of exits.ios

Input Specification:

Each input file contains one test case. For each case, the first line contains an integer N (in [3]), followed by N integer distances D1​​ D2​​ ⋯ DN​​, where Di​​ is the distance between the i-th and the (-st exits, and DN​​ is between the N-th and the 1st exits. All the numbers in a line are separated by a space. The second line gives a positive integer M (≤), with M lines follow, each contains a pair of exit numbers, provided that the exits are numbered from 1 to N. It is guaranteed that the total round trip distance is no more than 1.數組

Output Specification:

For each test case, print your results in M lines, each contains the shortest distance between the corresponding given pair of exits.ide

Sample Input:

5 1 2 4 14 9
3
1 3
2 5
4 1
 

Sample Output:

3
10
7

題目大意:

輸入一個N:表示有N個出口spa

輸入N個數:D1,D2,....DN,表示第 i 個 與 第 i + 1 個出口之間的距離code

輸入一個M:表示有M組數據orm

剩下M行,每行輸入2個數 i 和 j:表示 i 與 j 之間的最短距離htm

 

分析:

 Dn[i] :保存第 i 個與第 i + 1 個出口之間的距離blog

 sum :保存總距離(從1到N再到1,造成的一個環)ip

 

給出的兩個出口: exit1, exit2 ,計算 兩個出口之間的距離 s  ,再與 sum - s 比較,最小的那個就是最短距離

一開始想着用累加的方式,用D1,D2,DN計算出口之間的距離,可是這樣會超時

 

因此須要對距離進行預處理,獲得一個 數組 disc 

裏面保存了從 1 到 2, 從 1 到 3, 從 1 到 4 的距離

若是要計算從 2 到 4 的距離, 就至關因而 1到4的距離 - 1到2的距離 

 

須要注意的是:第一個出口必須小於第二個出口,不然就交換兩個值

 

 

 

 

C++實現:

#include <iostream>
#include <vector>
using namespace std;
int main() {
    int N;
    cin >> N;
    vector<int> Dn(N + 1);
    vector<int> disc(N + 1);
    int sum = 0;
    for (int i = 1; i <= N; ++i) {
        cin >> Dn[i];
        sum += Dn[i];
        disc[i] = sum;
    }
    int M;
    int exit1 = 0, exit2 = 0;
    cin >> M;
    for (int i = 0; i < M; ++i) {
        cin >> exit1 >> exit2;
        if (exit1 > exit2) {
            swap(exit1, exit2);
        }
        int shortest = 0;
        int temp = disc[exit2 - 1] - disc[exit1 - 1];
        shortest = temp < sum - temp ? temp : sum - temp;
        cout << shortest << endl;
    }
    return 0;
}

 

 

Java實現:

相關文章
相關標籤/搜索