A1046. Shortest Distance

题目描述#

  The task is really simple: given N exits on a high way which forms a simple cycle, you are supposed to tell the shortest distance between any pair of exits

输入格式#

  Each input file contains on test case. For each case, the first line contains an integer N (in[3, 105]), followed by N integer distances DD2 ... DN , where D1 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 exists  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 

题意#

  N个结点围成一个圈,相邻两个点之间的距离已知,且每次只能移动到相邻点。然后给出M个询问,每个询问给出两个数字A和B,即结点编号(1≤A,B≤N),求从A

号结点到B号结点最短距离

输入格式#

  每个输入文件包含一个测试用例

对于每种情况,第一行都包含一个整数N(在[3,105]中),后跟n个整数距离D1 D2 ... DN,其中D1是第i个与(i + 1)之间的距离出口,而DN在第N个出口和第一个出口之间。

一行中的所有数字都用空格分隔。 第二行给出一个正整数M(≤104),紧随其后的M行,每行包含一对出口号,条件是出口的编号从1到N。确保本地往返距离不超过 107

 

输入样例,有3个查询,分别是1,3;2,5;4,1

解题思路#

  • 这是一个圆,圆上两端点间距离的最小值,就是两点间的劣弧
复制代码
const int MAXN = 100000;
int dis[MAXN], A[MAXN];// dis 数组含义已说明,A[i] 存放i号与i+1 号顶点的距离
int main(int argc, char *argv[]) {
    int sum = 0, query, n, left, right;
    scanf("%d", &n);
    for(int i = 1; i <= n; i++){
        scanf("%d", &A[i]);
        sum += A[i];
        dis[i] = sum;// 初始化dis数组 
    } 
    scanf("%d", &query);
    for(int i = 0; i < query; i++){
        scanf("%d%d", &left, &right);
        if(left > right){
            swap(left, right);
        }
        int temp = dis[right - 1] - dis[left - 1];// 两端点沿顺时针的方向的弧 
        printf("%d\n", min(temp, sum - temp));// 选择劣弧输出 
    }
    return 0;    
}
复制代码
posted @   BigBender  阅读(182)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示
主题色彩