PAT做题日记:1003 Emergency

题目:

https://pintia.cn/problem-sets/994805342720868352/problems/994805523835109376

思路:

根据内存限制,邻接矩阵存储方法是可行的,因此先对图进行输入存储,再用dijkstra算法计算单源最短路路径。根据题目要求,每次遇到新的最短路径计数一次,同时对人数最大的路径累计人数。

AC代码

#include
#define MAX 500
#define INF 9999999
int main(){
    int n,edgenum,start,end;
    scanf("%d ",&n);
    int matrix[MAX][MAX];
    int people[MAX],dist[MAX],amount[MAX],pathcount[MAX];
    int mark[MAX];
    scanf("%d %d %d\n",&edgenum,&start,&end);
    scanf("%d ",&people[0]);
    for(int i=1;i<n;i++){
        scanf(" %d",&people[i]);
    }
    for (int i = 0; i < n; i++){
        dist[i] = INF;
        pathcount[i] = 1;
        mark[i] = 0;
        for (int j = 0; j < n; j++)
            matrix[i][j] = INF;
    }
    for(int j=0;j<edgenum;j++){
        int a,b,c;
        scanf("\n%d %d %d\n",&a,&b,&c);
        matrix[a][b] = c;
        matrix[b][a] = c;
    }
    dist[start] = 0;
    amount[start] = people[start];
    mark[start] = 1;
    int newP = start;
    while (newP != end){
        for (int i = 0; i < n; i++){
            if (mark[i] == 0){
                if (dist[i] > dist[newP] + matrix[newP][i]){
                    dist[i] = dist[newP] + matrix[newP][i];
                    amount[i] = amount[newP] + people[i];
                    pathcount[i] = pathcount[newP];
                }
                else if (dist[i] == dist[newP] + matrix[newP][i]){
                    pathcount[i] += pathcount[newP];
                    if (amount[i] < amount[newP] + people[i])
                        amount[i] = amount[newP] + people[i];
                }
            }
        }
        int dmin = INF;
        for (int i = 0; i < n; i++){
            if (mark[i] == 0 && dist[i] < dmin){
                dmin = dist[i];
                newP = i;
            }
        }
        mark[newP] = 1;
    }
    printf("%d %d\n",pathcount[end], amount[end]);
    return 0;
}

你可能感兴趣的:(图论,算法,c语言,dijkstra)