你来到一个迷宫前。该迷宫由若干个房间组成,每个房间都有一个得分,第一次进入这个房间,你就可以得到这个分数。还有若干双向道路连结这些房间,你沿着这些道路从一个房间走到另外一个房间需要一些时间。游戏规定了你的起点和终点房间,你首要目标是从起点尽快到达终点,在满足首要目标的前提下,使得你的得分总和尽可能大。现在问题来了,给定房间、道路、分数、起点和终点等全部信息,你能计算在尽快离开迷宫的前提下,你的最大得分是多少么?
输入
第一行4个整数n (<=500), m, start, end。n表示房间的个数,房间编号从0到(n - 1),m表示道路数,任意两个房间之间最多只有一条道路,start和end表示起点和终点房间的编号。
第二行包含n个空格分隔的正整数(不超过600),表示进入每个房间你的得分。
再接下来m行,每行3个空格分隔的整数x, y, z (0 < z<=200)表示道路,表示从房间x到房间y(双向)的道路,注意,最多只有一条道路连结两个房间, 你需要的时间为z。
输入保证从start到end至少有一条路径。
输出
一行,两个空格分隔的整数,第一个表示你最少需要的时间,第二个表示你在最少时间前提下可以获得的最大得分。
输入示例
3 2 0 2
1 2 3
0 1 10
1 2 11
输出示例
21 6
Dijkstra算法是一个经典的算法——他是荷兰计算机科学家Dijkstra于1959年提出的单源图最短路径算法,也是一个经典的贪心算法。所谓单源图 是规定一个起点的图,我们的最短路径都是从这个起点出发计算的。算法的适用范围是一个无向(或者有向图),所有边权都是非负数。
算法描述:
节点集合V = {}空集合,距离初始化。
节点编号0..n – 1, 起点编号0≤ s < n。
距离数组
起点 d[s] = 0
其他 d[i] = ∞, 0 ≤ i < n, i ≠ s。
循环n次
找到节点i 不属于 V,且d[i]值最小的节点i。
V = V + i
对所有满足j V的边(i, j) 更新d[j] = min(d[j] , d[i] + w(i, j))。
#include <cstdio>
#include <cstring>
#include <queue>
#include <utility>
#include <vector>
#include <functional>
using namespace std;
typedef long long ll;
const ll INF = 0x3f3f3f3f3f3f3f3f;
typedef pair<ll, int> Pair;
const int SIZE = 500 + 10;
struct Node {
int b;
ll w, aw;
Node(int y, ll z, ll _aw) {
b = y, w = z, aw = _aw;
}
bool operator < (const Node &n) const {
return w == n.w ? aw < n.aw : w > n.w;
}
};
int gra[SIZE][SIZE];
int vNum, eNum, in, out;
ll cost[SIZE], awardSum[SIZE];
int award[SIZE];
void Dijkstral(ll &ans1, ll &ans2) {
memset(awardSum, 1, sizeof(awardSum));
awardSum[in] = award[in];
memset(cost, 0x3f, sizeof(cost));
priority_queue<Node> q;
q.push(Node(in, 0, award[in]));
cost[in] = 0;
while (!q.empty()) {
Node head = q.top(); q.pop();
if (head.w > cost[head.b]) continue;
for (int i = 0; i < vNum; ++i) {
if (gra[head.b][i] >= INF) continue;
if (cost[i] > cost[head.b] + gra[head.b][i] ||
cost[i] == cost[head.b] + gra[head.b][i] &&
awardSum[i] < head.aw + award[i]) {
cost[i] = cost[head.b] + gra[head.b][i];
awardSum[i] = head.aw + award[i];
q.push(Node(i, cost[i], awardSum[i]));
}
}
}
ans1 = cost[out];
ans2 = awardSum[out];
}
int main() {
//freopen("in.txt", "r", stdin);
scanf("%d%d%d%d", &vNum, &eNum, &in, &out);
memset(gra, 0x3f, sizeof(gra));
for (int i = 0; i < vNum; ++i) {
scanf("%d", &award[i]);
}
for (int i = 0; i < eNum; ++i) {
int s, e, w;
scanf("%d%d%d", &s, &e, &w);
gra[s][e] = w;
gra[e][s] = w;
}
ll ans1 = 0, ans2 = 0;
Dijkstral(ans1, ans2);
printf("%lld %lld\n", ans1, ans2);
return 0;
}