zoukankan      html  css  js  c++  java
  • A1046. 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.

    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 DNis 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 #include<cstdio>
     2 #include<iostream>
     3 #include<vector>
     4 #include<algorithm>
     5 using namespace std;
     6 int main(){
     7     int N, M, sum = 0;
     8     vector<int> dst2src, re;
     9     scanf("%d", &N);
    10     int temp = 0;
    11     dst2src.push_back(temp);
    12     for(int i = 0; i < N; i++){
    13         scanf("%d", &temp);
    14         sum += temp;
    15         dst2src.push_back(sum);
    16     }
    17     scanf("%d", &M);
    18     for(int i = 0; i < M; i++){
    19         int a, b, L1, L2;
    20         scanf("%d%d", &a, &b);
    21         if(a > b) swap(a, b);
    22         L1 = dst2src[b - 1] - dst2src[a - 1];
    23         L2 = sum - L1;
    24         printf("%d
    ", min(L1, L2));
    25     }
    26     return 0;
    27 }
    View Code

    总结:1、可使用swap、min函数,引用algorithm即可。

       2、预处理:模拟题一般要考虑到时间复杂度,本题中有N个节点。若不做预处理,M组查询,会有M*N的复杂度。若在读入数据的时候,就计算出源点到该点的距离,则在查询时,a到b的距离可用a到源减去b到源,不用遍历。

       3、由于是一个环,a到b的距离只有顺逆时针两种可能。

  • 相关阅读:
    strcat strcpy 使用出现的问题汇总
    MySql Host is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts' 解决方法
    nginx 设置反响代理实现nginx集群
    js 去掉字符串最后一个字符
    二维数组 获取某键值集合
    oracle 序列
    递归数据查询
    oracle 递归查询
    jQuery EasyUI API 中文文档
    SecureCRT使用的技巧 键盘修改
  • 原文地址:https://www.cnblogs.com/zhuqiwei-blog/p/8428638.html
Copyright © 2011-2022 走看看