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

    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, 10^5^]), followed by N integer distances D~1~ D~2~ ... D~N~, where D~i~ is the distance between the i-th and the (i+1)-st exits, and D~N~ 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^.

    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开始), 这些数字围成一个圈,找出给出亮点的最小距离;
    第一次试的时候,超时了,因为处理的不是很完善
    解法:1.输入的时候,把所有的值加起来,计算的时候,只需要计算一个方向的距离就行, 另一个方向的距离用总的距离(即一个环的长度)来减就行;这种方法在最后一个测试点不能通过,因为每次计算都要重复的计算一些点的距离;
       2.对一进行一些小的改进,把数组中的值,保存为距离第一个点的距离,这样在计算的时候,把两点离第一个点的距离想减,就得到两点的距离。 为了方便计算,添加一个下标为0的点。
    描述点不是很清晰,还是看代码吧。
    关键在于,在输入的时候,就对数据进行处理,减少循环次数

     1 #include<iostream>
     2 using namespace std;
     3 int main(){
     4   int n, m, i, sum=0, *arr;
     5   cin>>n;
     6   arr = new int[n];
     7   for(i=0; i<n; i++){
     8     cin>>arr[i];
     9     sum += arr[i];
    10   }
    11   cin>>m;
    12   for(i=0; i<m; i++){
    13     int a, b, j, l=0;
    14     cin>>a>>b;
    15     if(a>b) swap(a, b);
    16     for(j=a; j<b; j++) l += arr[j-1];
    17     l = l<(sum-l)?l:(sum-l);
    18     cout<<l<<endl;
    19   }
    20   return 0;
    21 }

    修改之后点代码

     1 #include<iostream>
     2 using namespace std;
     3 int main(){
     4   int n, m, i, sum=0, *arr;
     5   cin>>n;
     6   arr = new int[n+1];
     7   arr[0]=0;
     8   for(i=1; i<=n; i++){
     9     cin>>arr[i];
    10     sum += arr[i];
    11     arr[i] += arr[i-1];
    12   }
    13   cin>>m;
    14   for(i=0; i<m; i++){
    15     int a, b, l=0;
    16     cin>>a>>b;
    17     if(a>b) swap(a, b);
    18     l = arr[b-1]- arr[a-1];
    19     l = l<(sum-l)?l:(sum-l);
    20     cout<<l<<endl;
    21   }
    22   return 0;
    23 }
    有疑惑或者更好的解决方法的朋友,可以联系我,大家一起探讨。qq:1546431565
  • 相关阅读:
    《Graph Attention Network》阅读笔记
    Spark 中的机器学习库及示例
    Spark 中 RDD的运行机制
    Spark 的 python 编程环境
    1.10系统调用和库函数
    nginx中的configure脚本
    nginx中的main函数
    IPv4,IPv6套接字地址结构
    unix网络编程中的地址转换函数
    有关nginx中Strings模块中ngx_explicit_memzero()函数的死区消除优化问题
  • 原文地址:https://www.cnblogs.com/mr-stn/p/9136634.html
Copyright © 2011-2022 走看看