PAT (Advanced Level) Practice 1003 Emergency

菜鸡一枚,第一次写这种题,写了好久。题目如下。

题目详情 (pintia.cn)https://pintia.cn/problem-sets/994805342720868352/problems/994805523835109376贴代码。

#include <iostream>
#include <vector>
#define INT_MAX 0x7fffffff
using namespace std;


int main(){
    //输入
    int n, m, c1, c2;
    cin >> n >> m >> c1 >> c2;
    
    vector<int> teamsNums(n);
    vector<vector<int>> graph(n, vector<int>(n, INT_MAX/2));

    for (int i=0; i<n; ++i) graph[i][i] = 0;
    for (int& teamNum:teamsNums) cin >> teamNum;
    for (int i=0; i<m; ++i){
        int x, y, u;
        cin >> x >> y >> u;
        graph[x][y] = u;
        graph[y][x] = u;
    }


    // Dij算法
    
    vector<int> shortestDis(n);
    vector<bool> visited(n, false);
    vector<int> pathNums(n, 1);//记录从c1到各个节点有几条最短路径
    vector<int> mostTeams(n, teamsNums[c1]);//记录几条最短路径中能召集到的队伍数目的最大值
    

    for (int i=0; i<n; ++i) {
        shortestDis[i] = graph[c1][i];
        if (i!=c1) mostTeams[i] += teamsNums[i];
        if (graph[c1][i] == INT_MAX/2) pathNums[i] = 0;
    }
    pathNums[c1] = 1;
    visited[c1] = true;
    
    for (int i=0; i<n-1; ++i){
        int minDis = INT_MAX/2;
        int minIndex = -1;
        for (int j=0; j<n; ++j){
            if (visited[j]) continue;
            if (shortestDis[j] <= minDis){
                minDis = shortestDis[j];
                minIndex = j;
            }
        }
        visited[minIndex] = true;

        for (int j=0; j<n; ++j){
            if (visited[j]) continue;
            if (shortestDis[j] > shortestDis[minIndex] + graph[minIndex][j]){
                shortestDis[j] = shortestDis[minIndex] + graph[minIndex][j];
                pathNums[j] = pathNums[minIndex];
                mostTeams[j] = teamsNums[j] + mostTeams[minIndex];
            }
            else if (shortestDis[j] == shortestDis[minIndex] + graph[minIndex][j]){
                pathNums[j] += pathNums[minIndex];
                mostTeams[j] = max(mostTeams[j], mostTeams[minIndex]+teamsNums[j]);
            }
        }
    }

    cout << pathNums[c2] << ' ' << mostTeams[c2] << endl;

    return 0;
}

        主要思想还是迪杰斯特拉算法过程中和动态更新pathNums和mostTeams两个数组,熟悉了还是挺简单的,第一次写可能还是有难度。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值