PAT-A 真题- 1046. Shortest Distance

发布于 / PAT-甲级 / 0 条评论

原题干:

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 <cstdio>
#include <algorithm>
#define MAXN 100010

int main(){
    int cnt, node[MAXN], allDistance = 0;
    scanf("%d", &cnt);
    for(int i = 1; i <= cnt; i++){
        scanf("%d", &node[i]);
        allDistance += node[i];
    }
    int query_cnt;
    scanf("%d", &query_cnt);
    while(query_cnt--){
        int start, end;
        scanf("%d %d", &start, &end);
        if(start > end) std::swap(start, end);
        int dis = 0;
        for(; start < end; start++)
            dis += node[start];
        printf("%d\n", std::min(dis, allDistance - dis));
    }
    return 0;
}

如果不出意料,你会得到测试点2运行超时的信息。这是因为测试点2的查询次数非常多,每次查询都要进行求和操作,在100ms根部完成不了

对此我们的解决方法是:创建缓存数组:cache,存放从点1到该点的距离信息。这样使用cache[终点-1]-cache[起点-1]就可以得到距离信息了。

代码如下:

#include <cstdio>
#include <algorithm>
#define MAXN 100010

int main(){
    int cnt, node[MAXN], allDistance = 0;
    int cache[MAXN];    //缓存数组
    scanf("%d", &cnt);
    for(int i = 1; i <= cnt; i++){
        scanf("%d", &node[i]);
        allDistance += node[i]; //总距离
        cache[i] = allDistance; //将1号节点到当前节点的距离写入缓存
    }
    int query_cnt;
    scanf("%d", &query_cnt);
    while(query_cnt--){
        int start, end;
        scanf("%d %d", &start, &end);
        if(start > end) std::swap(start, end);  //如果起点大于终点,交换
        /*int dis = 0;
        for(; start < end; start++)
            dis += node[start];*/
        int dis = cache[end-1] - cache[start-1];
        printf("%d\n", std::min(dis, allDistance - dis));
    }
    return 0;
}

转载原创文章请注明,转载自: 斐斐のBlog » PAT-A 真题- 1046. Shortest Distance
目前还没有评论,快来抢沙发吧~