原题地址
https://pintia.cn/problem-sets/1268384564738605056/problems/1286606445168746498
注意事项
1.注意自己添加一个超级源点和超级汇点,否则过不了多起点和多终点的数据。
2.注意题目要求的关键活动输出规则:任务开始的交接点编号小者优先,起点编号相同时,与输入时任务的顺序相反。
所以获得关键路径之后要先存起来进行排序,之后再输出。
(我是当作题目给的都是按照顺序排的,然后我排序的时候直接逆序)
参考代码
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
typedef double db;
typedef long long LL;
typedef vector<int> VI;
const int inf = 2e9;
const LL INF = 8e18;
const int maxn = 110;
struct node{
int v, w;
};
struct task{
int s, e;
};
bool cmp(task a, task b) {
if (a.s != b.s) return a.s < b.s;
return a.e > b.e;
}
vector<vector<node> > G(maxn);
vector<task> critical;
int n, m, ve[maxn] = {0}, vl[maxn];
int inDegree[maxn] = {0}, outDegree[maxn] = {0};
stack<int> topOrder;
int topSort() {
queue<int> q;
int cnt = 0;
for (int i = 1; i <= n + 2; i++) {
if (!inDegree[i]) {
//cout << i << endl;
q.push(i);
}
}
while (!q.empty()) {
int u = q.front();
//cout << "u:" << u << endl;
q.pop();
topOrder.push(u);
cnt++;
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i].v, w = G[u][i].w;
if (--inDegree[v] == 0) q.push(v);
if (ve[u] + w > ve[v]) {
ve[v] = ve[u] + w;
}
}
}
if (cnt == n + 2) return ve[n + 2];
else return -1;
}
void criticalPath() {
fill(vl, vl + maxn, ve[n + 2]); //要初始化为最长路径
while (!topOrder.empty()) {
int u = topOrder.top();
topOrder.pop();
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i].v, w = G[u][i].w;
if (vl[v] - w < vl[u]) {
vl[u] = vl[v] - w;
//cout << "vl[u]:" << vl[u] << endl;
}
}
}
for (int u = 1; u <= n; u++) {
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i].v, w = G[u][i].w;
int e = ve[u], l = vl[v] - w;
//cout << e << ' ' << l << endl;
if (e == l && v <= n) {
//printf("%d->%d\n", u, v);
critical.pb(task{u, v});
}
}
}
sort(critical.begin(), critical.end(), cmp);
for (int i = 0; i < critical.size(); i++) {
printf("%d->%d\n", critical[i].s, critical[i].e);
}
}
int main() {
scanf("%d%d", &n, &m);
int a, b, w;
for (int i = 0; i < m; i++) {
scanf("%d%d%d", &a, &b, &w);
G[a].pb(node{b, w});
inDegree[b]++;
outDegree[a]++;
}
//为入度为0的点添加超级源点n+1,边权为0
//为出度为0的点添加超级汇点n+2,边权为0
for (int i = 1; i <= n; i++) {
if (inDegree[i] == 0) {
G[n + 1].pb(node{i, 0});
inDegree[i]++;
}
if (outDegree[i] == 0) {
G[i].pb(node{n + 2, 0});
inDegree[n + 2]++;
}
}
int ans = topSort();
if (ans == -1) printf("0");
else printf("%d\n", ans);
criticalPath();
return 0;
}