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
  • 相关阅读:
    paste 合并文件
    split 分割文件
    cut 从文本中提取一段文字并输出
    tailf 跟踪日志文件
    tail 显示文件内容尾部
    给Linux系统新增加一块硬盘
    Centos7+httpd+fastcgi安装提示错误
    Redhat 7使用CentOS 7的Yum网络源
    windows7下cmd窗口使用ssh命令
    PHP set_error_handler() 函数
  • 原文地址:https://www.cnblogs.com/princecoding/p/5813957.html
Copyright © 2011-2022 走看看