zoukankan      html  css  js  c++  java
  • 问题 E: Shortest Distance (20)

    问题 E: Shortest Distance (20)

    时间限制: 1 Sec  内存限制: 32 MB
    献花: 181  解决: 83
    [献花][花圈][TK题库]

    题目描述

    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, 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.

    输出

    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

    参考代码:

    #include<stdio.h>

    #include<algorithm>

    using namespace std;

    int main(){

        int n, m;

        int temp;

        int start, end;

        int distance=0;

        int a[10000]={};

    //  int b[100]={0};

        scanf("%d", &n);

        for(int i=1;i<=n;i++){

            scanf("%d",&temp);

            distance+=temp;

            a[i+1]=a[i]+temp;

        }

    //  printf("%d ", distance);

        scanf("%d", &m);

        for(int i=0;i<m;i++){

            int distance1=0;

            scanf("%d %d",&start,&end);

            distance1=abs(a[start]-a[end]);

            printf("%d",min(distance1,distance-distance1));

           

    //      for(int j=min(start, end);j<max(start, end);j++){

    //          distance1+=a[j-1];

    //          if(distance1<distance-distance1){

    //              b[i]=distance1;

    //          }else{

    //              b[i]=distance-distance1;

            }

    //    for(int i=0;i<m;i++){

    //        printf("%d ", b[i]);

    //    }

            return 0;

            }

     输入n代表后面输入n个数,这些数不需要用数组保存,只要用普通变量temp保存,立马做运算处理即可,distance变量保存总距离,表示每输入的一个数与第一点的距离的结果需要用数组a[10000]保存,m代表即将输入的组数,每一组的两个数表示起点和终点,它们中间的距离等于起点到第一点的距离减去终点到第一点的距离的绝对值,最后输出printf("%d",min(distance1,distance-distance1))

    这题尤其要注意时间限制,注释的部分代码使用了多次for循环,导致时间超时,问题就在于没有在输入的时候就存储从1开始到各点之间的距离值,导致后来还要用for循环计算temp。如果顶点数n值很大的话,似乎确实很耗时。

    使用min()函数,需要有头文件#include<algorithm>和using namespace std;

  • 相关阅读:
    深度解析U-Boot网络实现(长篇好文)
    优化嵌入式Linux的启动时间之内核
    优化嵌入式Linux的启动时间之文件系统
    Java安全之 ClassLoader类加载器
    Java 审计之xss审计要点
    Java审计之命令执行篇
    Java审计之文件操作漏洞
    Java 审计 之过滤器防御xss
    Java 审计之SSRF篇(续)
    Java 审计之SSRF篇
  • 原文地址:https://www.cnblogs.com/zhhjthing/p/7802186.html
Copyright © 2011-2022 走看看