题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805523835109376
这题是传统单DFS算法的应用,直接在更新最短距离那一步把事情都做完。
代码
#include<vector>#include<algorithm>#include<cstdio>#include<iostream>using namespace std;const int maxn = 510;const int INF = 1000000000;int n, m, c1, c2;int temp_c1, temp_c2, temp_d;int weight[maxn], G[maxn][maxn];int d[maxn], num[maxn], w[maxn];//d[maxn]是起点到各点的最短距离bool vis[maxn] = {false};void Dijkstra(){fill(d, d + maxn, INF);fill(w, w + maxn, 0);fill(num, num + maxn, 0);d[c1] = 0;w[c1] = weight[c1];num[c1] = 1;for(int i = 0; i < n; i++){//循环n次int u = -1, min = INF;for(int j = 0; j < n; j++){//找到最小的if(vis[j] == false && d[j] < min){u = j;min = d[j];}}if(u == -1) return;//更新d[]vis[u] = true;for(int v = 0; v < n; v++){if(vis[v] == false && G[u][v] != INF){//没被访问过且可达if(d[u] + G[u][v] < d[v]){d[v] = d[u] + G[u][v];num[v] = num[u];w[v] = w[u] + weight[v];} else if (d[u] + G[u][v] == d[v]){if(weight[v] + w[u] > w[v]){w[v] = w[u] + weight[v];}num[v] += num[u];}}}}}int main(){scanf("%d%d%d%d", &n, &m, &c1, &c2);for(int i = 0; i < n; i++) scanf("%d", &weight[i]);fill(G[0], G[0] + maxn * maxn, INF);for(int i = 0; i < m; i++){scanf("%d %d %d", &temp_c1, &temp_c2, &temp_d);G[temp_c1][temp_c2] = temp_d;G[temp_c2][temp_c1] = temp_d;}Dijkstra();printf("%d %d",num[c2], w[c2]);return 0;}
