有点复杂,考了两个知识点,拓扑排序+dijkstra,但是后三个测试点错误,目前不知道哪里错了><
等一个有缘人
#include <bits/stdc++.h>
using namespace std;
struct Pair {
int neighbor, score, voucher;
Pair(int n, int s, int v): neighbor(n), score(s), voucher(v) {}
};
int N, M, T1, T2, S, D, K;
vector<vector<Pair>> neighbors;
vector<int> in; //入度
vector<int> queries;
bool hasCircle();
vector<int>* dijkstra();
int main() {
cin >> N >> M;
neighbors.resize(N + 1, vector<Pair>()); //入度为0的点可能不止一个,增加一个哨兵点,只需一次dijkstra
in.resize(N + 1, 0);
for (int i = 0; i < M; ++i) {
cin >> T1 >> T2 >> S >> D;
Pair p(T2 + 1, S, D);
neighbors[T1 + 1].emplace_back(p);
in[T2 + 1] += 1;
}
vector<int> oldin(in);
cin >> K;
queries.resize(K);
for (int i = 0; i < K; ++i) {
cin >> queries[i];
}
for (int i = 1; i <= N; ++i) {
if (in[i] == 0) {
++in[i];
Pair p(i, 0, 0);
neighbors[0].emplace_back(p);
}
}
if (hasCircle()) {
cout << "Impossible." << endl;
for (int& x: queries) {
if (oldin[x + 1] == 0) {
printf("You may take test %d directly.\n", x);
} else {
cout << "Error." << endl;
}
}
} else {
cout << "Okay." << endl;
//求入度为0点的dijkstra
vector<int>* pre = dijkstra();
for (int& x: queries) {
if (oldin[x + 1] == 0) {
printf("You may take test %d directly.\n", x);
} else {
string s = "";
s += to_string(x);
while (true) {
x = (*pre)[x + 1] - 1;
if (x == -1) {
break;
}
s += ">-";
s += to_string(x);
}
reverse(s.begin(), s.end());
cout << s << endl;
}
}
}
return 0;
}
bool hasCircle() {
queue<int> tmpq;
tmpq.push(0);
vector<int> tmpin(in);
int res = 0;
while (!tmpq.empty()) {
int i = tmpq.front();
tmpq.pop();
res++;
for (auto& p: neighbors[i]) {
int j = p.neighbor;
if (--tmpin[j] == 0) {
tmpq.push(j);
}
}
}
return res == N + 1 ? false : true;
}
vector<int>* dijkstra(){
vector<int> scores(N + 1, INT_MAX);
vector<int> vouchers(N + 1, 0);
vector<int> pre(N + 1, -1);
vector<int> visited(N + 1, 0);
scores[0] = 0;
while (true) {
int u = -1, minScore = INT_MAX;
for (int i = 0; i <= N; ++i) {
if (visited[i] == 0 && scores[i] < minScore) {
u = i;
minScore = scores[i];
}
}
if (u == -1) {
break;
}
visited[u] = 1;
for (auto& p: neighbors[u]) {
if (visited[p.neighbor] == 0) {
if (scores[p.neighbor] > scores[u] + p.score) {
scores[p.neighbor] = scores[u] + p.score;
vouchers[p.neighbor] = vouchers[u] + p.voucher;
pre[p.neighbor] = u;
} else if (scores[p.neighbor] == scores[u] + p.score) {
if (vouchers[p.neighbor] < vouchers[u] + p.voucher) {
vouchers[p.neighbor] = vouchers[u] + p.voucher;
pre[p.neighbor] = u;
}
}
}
}
}
vector<int>* values = new vector<int>(pre);
return values;
}