zoukankan      html  css  js  c++  java
  • pat 1046. Shortest Distance (20)

    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
    解:这一题我最初用的是Floyd,但是会卡内存,100000*100000的数组想都不敢想,然后就一直卡,后来想想20分的题目应该用不到Floyd算法,把问题简化了,我把路径想象成一条带子,拿测试样例举例,1-5,这条带子就是1-2-3-4-5-1-2-3-4,开一维数组,数组最大也不超过2*100000,根据起点和终点相减(这里我用的for循环计算,比如说4和1的最短路径,我就是for(i=1;i<4;i++),后来证明错误问题就出现在这里),得到绝对值temp,再得到边数之和sum-temp和temp中的较小值,即为目标最短距离值(这一点,和正确的思路已经相差不多了,好痛心,脑袋太笨),但是pat的第三个测试会超时。

      后来百度了下别人的做法,http://www.2cto.com/kf/201311/254357.html,感觉很受用,我的问题就在于没有在输入的时候就存储从1开始到各点之间的距离值,导致后来还要用for循环计算temp。如果顶点数n值很大的话,似乎确实很耗时。

    自己错误在:我用数组存储相邻边的距离,如1-2的距离,2-3的距离,3-4的距离等,而不是1-2,1-3,1-4的距离,导致后来需要使用for循环累加求解temp。

    下面贴上代码:

    #include<iostream>
    #include<cstdlib>
    #include<cstdio>
    #include<cmath>
    using namespace std;
    
    int main()
    {
        int n,m;  //n表示边数,m表示求最短路的测试个数
        while(cin>>n)
        {
            int *a=new int[n+3];  //动态生成
            int temp=0;   //临时存储边值,初始化
            int sum=0;    //所有边值之和,初始化
            a[1]=0;
            for(int i=1;i<=n;i++)
            {
                cin>>temp;
                sum+=temp;
                a[i+1]=a[i]+temp;
            }
            cin>>m;
            int beg,en;  //起点beg和终点en
            for(int i=1;i<=m;i++)
            {
                cin>>beg>>en;
                temp=abs(a[beg]-a[en]);
                cout<<min(temp,sum-temp)<<endl;
            }
        }
    }
    

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    power designer 绘制E-R 图
    git 的证书重新设置,以及如何让git 记住提交的用户名和密码
    weblogic的安装和注意的问题以及在idea怎么用weblogic启动一个web服务
    java的URI和URL到底是什么
    怎么把centos虚拟机zip文件导入vm虚拟机中
    gogole调试请求体的数据怎么知道
    Javascript数据类型——number类型
    Javascript类型——boolean类型
    Javascript数据类型——undefined和null的异同
    第3章,基本概念
  • 原文地址:https://www.cnblogs.com/Tobyuyu/p/4965303.html
Copyright © 2011-2022 走看看