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.

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

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

#include <iostream>
using namespace std;

int main(int argc, const char * argv[]) {
    int n;
    cin >> n;
    int dis[n+1];
    int t, sum = 0;;
    for (int i = 1; i <= n; i++) {
        cin >> t;
        sum += t;
        dis[i] = sum;
    }
    
    int m, l, r;
    cin >> m;
    for (int i = 0; i < m; i++) {
        cin >> l >> r;
        if(l > r) swap(l, r);
        t = dis[r - 1] - dis[l - 1];
        int ans = min(t, sum - t);
        cout << ans << endl;
    }
    
    return 0;
}





目录
相关文章
|
安全 Java 开发工具
Git企业开发级讲解(四)
Git企业开发级讲解(四)
114 0
|
Kubernetes 安全 Linux
开源Chart包安全分析发布,阿里云视角容器安全基线的重要性
云原生环境下,容器成为了软件开发过程中打包与分发的标准。
开源Chart包安全分析发布,阿里云视角容器安全基线的重要性
|
7月前
|
Java
课时13:Java数据类型划分(布尔型)
观察布尔型的操作。布尔是一位数学家的名字,这个布尔发明了两个单词:True、False(一个表示真一个表示假)。一般布尔类型都只表示逻辑的计算结果。
163 9
|
JSON 安全 Java
Spring Security 与 JWT、OAuth 2.0 整合详解:构建安全可靠的认证与授权机制
Spring Security 与 JWT、OAuth 2.0 整合详解:构建安全可靠的认证与授权机制
1332 0
|
传感器 监控
LabVIEW控制Arduino采集DHT11温湿度数值(进阶篇—4)
在多数情况下,测量温度的同时需要测量湿度,本篇博文将介绍使用DHT11温湿度传感器、Arduino Uno和LabVIEW组成温湿度测量系统,可用于粮仓等场合的温湿度监控。
|
设计模式 开发框架 算法
【QML 创建界面】QML界面的动态创建及其其他方法 (Dynamic Creation of QML Interfaces and Other Methods)
【QML 创建界面】QML界面的动态创建及其其他方法 (Dynamic Creation of QML Interfaces and Other Methods)
1539 0
|
NoSQL JavaScript 前端开发
部署自己的MOCK(一)
本文适合团队内部没有MOCK服务,对mock有实际需要的小伙伴。
部署自己的MOCK(一)
|
JavaScript
js实现跨浏览器tab选项卡页通信、传参,监听localStorage.变量的实时变化,实现打开多个浏览器页面窗口相互可以传参通信
js实现跨浏览器tab选项卡页通信、传参,监听localStorage.变量的实时变化,实现打开多个浏览器页面窗口相互可以传参通信
|
算法 Java 测试技术
【JUC基础】17. 并发编程常见问题
多线程固然可以提升系统的吞吐量,也可以最大化利用系统资源,提升相应速度。但同时也提高了编程的复杂性,也提升了程序调试的门槛。今天就来汇总一些常见的并发编程中的问题。
816 2