C++代码:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;
typedef pair<int, int> node;
const int N = 1010, M = N * N;
int h[N], d[N], cd[N], e[M], ne[M], w[M], v[M], idx;
int q[N];
int dist[N], sum[N], pre[N];
bool st[N];
int n, m, k;
void add(int a, int b, int p, int q)
{
e[idx] = b, w[idx] = p, v[idx] = q, ne[idx] = h[a], h[a] = idx++;
}
// 判断有向图是否有环
bool topsort()
{
int hh = 0, tt = -1;
for (int i = 0; i < n; i++) if (!d[i]) q[++tt] = i;
while (hh <= tt)
{
int t = q[hh++];
for (int i = h[t]; ~i; i = ne[i])
{
int j = e[i];
d[j]--;
if (!d[j]) q[++tt] = j;
}
}
if (tt == n - 1) return false;
return true;
}
void dijkstra()
{
memset(dist, 0x3f, sizeof dist);
dist[n] = 0, pre[n] = -1;
priority_queue<node, vector<node>, greater<node>> heap;
heap.push({ 0, n });
while (!heap.empty())
{
auto head = heap.top();
heap.pop();
int distance = head.first, t = head.second;
if (st[t]) continue;
st[t] = true;
for (int i = h[t]; ~i; i = ne[i])
{
int j = e[i];
if (dist[j] > distance + w[i])
{
dist[j] = distance + w[i];
sum[j] = sum[t] + v[i];
pre[j] = t;
heap.push({ dist[j], j });
}
else if (dist[j] == distance + w[i] && sum[j] < sum[t] + v[i])
{
sum[j] = sum[t] + v[i];
pre[j] = t;
}
}
}
}
int main()
{
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
while (m--)
{
int a, b, p, q;
scanf("%d%d%d%d", &a, &b, &p, &q);
add(a, b, p, q);
d[b]++;
}
// 做完拓扑排序, d已经被清空
memcpy(cd, d, sizeof d);
bool circle = topsort();
if (circle) puts("Impossible.");
else
{
puts("Okay.");
// 建立虚拟源点
for (int i = 0; i < n; i++)
if (!cd[i]) add(n, i, 0, 0);
dijkstra();
}
scanf("%d", &k);
while (k--)
{
int x;
scanf("%d", &x);
if (circle)
{
if (!cd[x]) printf("You may take test %d directly.\n", x);
else puts("Error.");
}
else
{
if (!cd[x]) printf("You may take test %d directly.\n", x);
else
{
vector<int> path;
for (int i = x; ~pre[i]; i = pre[i]) path.push_back(i);
reverse(path.begin(), path.end());
printf("%d", path[0]);
for (int i = 1; i < path.size(); i++) printf("->%d", path[i]);
puts("");
}
}
}
return 0;
}