PAT Class A 1046 Shortest Distance (20 points)|C++ implementation

1. Title description

原题链接
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:

Insert picture description here

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

Two, problem-solving ideas

The main idea is: N exits form a circle, give the distance between each exit and the next exit, then enter two exits arbitrarily, and ask us to output the shortest distance between them. This question is very easy to think about, because each exit constitutes a circle, and our shortest distance is either to turn in a clockwise direction or to turn in a counterclockwise direction. We can use the array fromSt to represent the distance of each exit from the starting point (clockwise). Then, according to the two exits given by the title, we can find the clockwise distance, and then subtract this distance from the circumference of the entire circle. The distance in the counterclockwise direction can be compared and output.

Three, AC code

#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 100010;
int edge[maxn] = {
    
    0};   //存放第i条边的长度
int fromSt[maxn] = {
    
    0};
int N;
int main()
{
    
    
    int M, a, b, ans;
    scanf("%d", &N);
    for(int i=1; i<=N; i++)
    {
    
    
        scanf("%d", &edge[i]);
        fromSt[i] = fromSt[i-1] + edge[i-1];
    }
    scanf("%d", &M);
    for(int i=0; i<M; i++)
    {
    
    
        scanf("%d%d", &a, &b);
        int clock = fromSt[max(a, b)] - fromSt[min(a, b)];
        int counter = fromSt[N] + edge[N] - clock;
        ans = clock > counter ? counter : clock;
        printf("%d\n", ans);
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_42393947/article/details/108592109