PAT A1046 Shortest Distance (20 分)

题目提交一直出现段错误,经过在网上搜索得知是数组溢出,故将数组设置的大一点
AC代码

#include <cstdio>
#include <algorithm>
#define N 11000

using namespace std;

int main(){
    #ifdef ONLINE_JUDGE
    #else
        freopen("1.txt", "r", stdin);
    #endif // ONLINE_JUDGE
    int dis[N];
    int dis_sum[N] = {0};
    int n, times, small, big, sum = 0;;
    scanf("%d", &n);    //输入点的个数
    for(int i = 1; i < n + 1; i++) {//输入点与点之间的距离
        scanf("%d", &dis[i]);
        sum += dis[i];
        dis_sum[i] = sum;
    }
    /*for(int i = 1; i < n + 1; i++) {
        printf("--- %d --- %d ---\n", dis[i], dis_sum[i]);
    }*/
    scanf("%d", &times);
    for(int i = 0; i < times; i++) {
        int temp1, temp2, right, left, big, small, shortest;
        scanf("%d%d", &left, &right);
        //printf("%d %d")
        big= max(left, right);
        small = min(left, right);
        temp1 = dis_sum[big - 1] - dis_sum[small - 1]; //从右开始算的距离
        //temp2 = dis_sum[small - 1] + (sum - dis_sum[big - 1]); //从左开始算的距离
        temp2 = sum - temp1;
        shortest = min(temp1, temp2);
        //printf("small:%d---dis_sum[small]:%d---big:%d---dis_sum[big]:%d---temp1:%d---temp2:%d---shortest:%d\n", small, dis_sum[small], big, dis_sum[big], temp1, temp2, shortest);
        printf("%d\n", shortest);
    }
    return 0;
}
posted @ 2019-07-19 15:36  哨音  阅读(243)  评论(0编辑  收藏  举报