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.
输入
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.
输出
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
一开始的方法超时

#include <cstdio>
#include <cstring>
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int a,b;
    int m[100010]={0};
    int x,y;
    int p,q;
    int tol=0;
   scanf("%d",&a);

        for(int i=1;i<=a;i++)
        {
            scanf("%d",&m[i]);
        }
        scanf("%d",&b);
        for(int i=0;i<b;i++)
        {
            scanf("%d%d",&x,&y);
            if(x==y)
                printf("0\n");
            if(x>y)
            {
                int temp = x;
                x=y;
                y=temp;
            }
            p=0;q=0;
            for(int i=x;i<y;i++)
                p+=m[i];
            for(int i=y;i<=a;i++)
                q+=m[i];
            for(int i=1;i<x;i++)
                q+=m[i];
            if(p<q)
                printf("%d\n",p);
            else
                printf("%d\n",q);
        }
    return 0;
}

后来利用前缀和改进

#include <cstdio>
#include <cstring>
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int a,b;
    int m[100010]={0};
    int x,y;
    int p,q;
    int tol=0;
   scanf("%d",&a);

        for(int i=1;i<=a;i++)
        {
            cin>>m[i];
            tol+=m[i];
            m[i]+=m[i-1];
        }
        cin>>b;
        for(int i=0;i<b;i++)
        {
            cin>>x>>y;
            if(x==y)
                cout<<0<<endl;
            if(x>y)
            {
                int temp = x;
                x=y;
                y=temp;
            }
            p=0;q=0;
            p=m[y-1]-m[x-1];
            q=tol-p;
            if(p<q)
                cout<<p<<endl;
            else
                cout<<q<<endl;

        }

    return 0;
}

发布了21 篇原创文章 · 获赞 0 · 访问量 396

猜你喜欢

转载自blog.csdn.net/weixin_41605876/article/details/104589012