码迷,mamicode.com
首页 > 其他好文 > 详细

Shortest Distance

时间:2020-07-26 15:22:02      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:class   限制   ret   round   input   rms   contain   tmp   out   

题目描述

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;
}

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

技术图片

 

 

 

 

Shortest Distance

标签:class   限制   ret   round   input   rms   contain   tmp   out   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!