菜鸡一枚,第一次写这种题,写了好久。题目如下。
题目详情 (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两个数组,熟悉了还是挺简单的,第一次写可能还是有难度。