zoukankan      html  css  js  c++  java
  • PAT 1046

    1046. Shortest Distance (20)

    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.

    Input Specification:

    Each input file contains one test case. For each case, the first line contains an integer N (in [3, 105]), followed by N integer distances D1 D2 ... DN, where Di is the distance between the i-th and the (i+1)-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 (<=104), 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 107.

    Output Specification:

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

    Sample Input:
    5 1 2 4 14 9
    3
    1 3
    2 5
    4 1
    
    Sample Output:
    3
    10
    7
    这题做这么久真是没治了,本来不是很难的一题,被自己蠢到了……
    #include <iostream>
    #include <cmath>
    using namespace std;
    
    int exitPort[100005]; //开始少一个0,可见细心的重要性, 10^5并不是10005,不是五位数谢谢
    
    int main()
    {
        int N;
        cin >> N;
    
        exitPort[1] = 0;
    
        int sum = 0;
        for(int i = 2; i <= N + 1; i++)
        {
            int road;
            cin >> road;
            sum += road;
            exitPort[i] = sum;
        }
    
        int M;
        cin >> M;
        while(M--)
        {
            int in, out;
            cin >> in >> out;
    
            if(sum - abs(exitPort[out] - exitPort[in]) > abs(exitPort[out] - exitPort[in])) //由于写成了abs(sum - exitPort[out] + exitPort[in]) 有一个点一直没过
            {
                cout << abs(exitPort[out] - exitPort[in]) << endl;
            }
            else
                cout << sum - abs(exitPort[out] - exitPort[in]) << endl;
        }
    
        return 0;
    }
    这题唯一的收获就是定义数组的时候最好不要用exit做名称,有的OJ来说, exit是内置的变量,可能会有编译错误,因此修改为exitPort
  • 相关阅读:
    最近公共祖先LCA Tarjan 离线算法
    HDU 2586 How far away? LCA 转化成RMQ
    最近公共祖先 Least Common Ancestors(LCA)算法 --- 与RMQ问题的转换
    RMQ ---- ST(Sparse Table)算法
    二维计算几何系列(一) -------- 数据结构
    Goalng基础语法-输入和输出
    Golang基础语法-运算符
    Golang基础语法-数据类型
    Golang基础语法-常量
    Golang基本语法-变量
  • 原文地址:https://www.cnblogs.com/princecoding/p/5813957.html
Copyright © 2011-2022 走看看