Shortest Distance

题目描述

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.

输入

Each input file contains one test case. For each case, the first line contains an integer N (in [3, 10^5]), 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 (<=10^4), 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 10^7.

输出

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

样例输入

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

样例输出

3
10
7

解析

在一个环形的高速路口有很多节点,输入每个出口节点之间的距离。输入需要查询的出口的编号,最后输出这两个节点之间的最短路程。

方法一:依次输入每个节点之间的距离放入一个数组。输入两个节点编号,最后按照顺时针和逆时针两个方向计算二者之间的距离。用for循环从编号较小的节点加到编号较大的节点,得出顺时针的距离。再用整个环形圆圈整个长度减去顺时针的距离,得到逆时针的距离。

#include<iostream>
#include<cmath>
using namespace std;
int main(){
    int n;
    cin>>n;
    int* roads=new int[n];
    for(int i=0;i<n;i++){
        cin>>roads[i];
    }
    int t;
    cin>>t;
    int all=0;
    for(int i=0;i<n;i++){//环形通道总长度 
            all=all+roads[i];
    }
    for(int i=0;i<t;i++){
        int tmpa,tmpb;
        int a,b;
        int dis1=0,dis2=0;
        cin>>tmpa>>tmpb;
        a=tmpa-1;
        b=tmpb-1;
        int min,max;
        if(a>b){
            min=b;
            max=a;
        }
        else if(a<b){
            min=a;
            max=b;
        }
        for(int j=min;j<max;j++){//顺时针 
            dis1=dis1+roads[j];
        }
        dis2=all-dis1;//逆时针
        if(dis1>dis2){
            cout<<dis2<<endl;
        } 
        else{
            cout<<dis1<<endl;
        }
    }
    return 0;
}

但是遇到时间超过限制的问题

 需要减少时间消耗,思路:使用C语言的输入输出减少时间,间少for循环的轮次减少时间。

方法二:记录1号点到各点之间的顺时针距离。以后求各点之间的距离就只用二者相减

#include<iostream>
#include<cmath>
#include<cstdio>
using namespace std;
int main(){
    int n,all=0,temp;
    scanf("%d",&n);
    int* roads=new int[n+1];
    for(int i=0;i<n;i++){
        scanf("%d",&temp);
        all=all+temp;
        roads[i+1]=roads[i]+temp;//记录从1号点一直到n号点之间的距离 
    }
    int t;
    scanf("%d",&t);
    for(int i=0;i<t;i++){//次数 
        int tmpa,tmpb;
        int a,b;
        int dis1=0,dis2=0;
        scanf("%d %d",&tmpa,&tmpb);
        a=tmpa-1;
        b=tmpb-1;
        int min,max;
        if(a>b){
            min=b;
            max=a;
        }
        else if(a<b){
            min=a;
            max=b;
        }
        dis1=roads[max]-roads[min];//顺时针 
        dis2=all-dis1;//逆时针
        if(dis1>=dis2){
            printf("%d
",dis2);
        } 
        else{
            printf("%d
",dis1);
        }
    }
    return 0;
}


原文地址:https://www.cnblogs.com/ak918xp/p/13379360.html