• PAT1046: Shortest Distance


    1046. Shortest Distance (20)

    时间限制
    100 ms
    内存限制
    65536 kB
    代码长度限制
    16000 B
    判题程序
    Standard
    作者
    CHEN, Yue

    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

    思路

    1.直接用累加求和,结果最后一项测试用例超时。
    2.开一个二维数组暴力枚举出所有可能的情况,检测时直接输出对应情况,结果内存超了(最坏情况数组大小100001 * 100001)。
    3.保存每一个目标点到起始点的road[i],那么任意两个点s,e的距离可以通过road[s]-road[e]计算出来,而不用再去一步步累加,所以不会超时。而且这种解决方案最坏情况开辟的数组大小为100001,不会超内存。

    代码
    #include<iostream>
    #include<vector>
    #include<math.h>
    using namespace std;
    
    
    int main()
    {
       int N;
       while(cin >> N)
       {
           vector<int> road(N + 2,0);
           int sum = 0;
           for(int i = 1;i <= N;i++)
           {
               int value;
               cin >> value;
               road[i + 1] = road[i] + value;
               sum += value;
           }
            int M;
            cin >> M;
            while(M--)
            {
                int s,e;
                cin >> s >> e;
                int path = abs(road[s] - road[e]);
                cout << min(path,sum - path) << endl;
            }
       }
    }
  • 相关阅读:
    🍖权限管理之高级权限 ACL
    C#中的interface没那么简单【转】
    URL与物理文件的分离【转】
    共享工作簿
    关于runas explorer.exe 的问题
    但愿汶川早日恢复平静但愿灾区人民早日重建家园!
    正确删除系统隐藏的设备
    vim配置文件.vimrc
    outlook中的邮件归档
    Windows 系统环境变量
  • 原文地址:https://www.cnblogs.com/0kk470/p/7638449.html
Copyright © 2020-2023  润新知