51 lines
1.3 KiB
C++
51 lines
1.3 KiB
C++
// P5960:求任意一组差分约束可行解。C++11。
|
|
#include <iostream>
|
|
#include <vector>
|
|
#include <queue>
|
|
using namespace std;
|
|
using ll = long long;
|
|
struct Edge { int v, w; };
|
|
|
|
bool solve(const vector<vector<Edge>>& g, vector<ll>& dis) {
|
|
int n = static_cast<int>(g.size()) - 1;
|
|
dis.assign(n + 1, 0);
|
|
vector<int> len(n + 1, 0);
|
|
vector<bool> inq(n + 1, true);
|
|
queue<int> q;
|
|
for (int i = 1; i <= n; ++i) q.push(i);
|
|
while (!q.empty()) {
|
|
int u = q.front(); q.pop();
|
|
inq[u] = false;
|
|
for (auto e : g[u]) {
|
|
int v = e.v;
|
|
ll nd = dis[u] + e.w;
|
|
if (nd >= dis[v]) continue;
|
|
dis[v] = nd;
|
|
len[v] = len[u] + 1;
|
|
if (len[v] >= n) return false;
|
|
if (!inq[v]) {
|
|
q.push(v); inq[v] = true;
|
|
}
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
int main() {
|
|
ios::sync_with_stdio(false);
|
|
cin.tie(nullptr);
|
|
int n, m;
|
|
if (!(cin >> n >> m)) return 0;
|
|
vector<vector<Edge>> g(n + 1);
|
|
for (int i = 0; i < m; ++i) {
|
|
int a, b, w; cin >> a >> b >> w;
|
|
g[b].push_back({a, w});
|
|
}
|
|
vector<ll> dis;
|
|
if (!solve(g, dis)) cout << "NO\n";
|
|
else {
|
|
for (int i = 1; i <= n; ++i)
|
|
cout << dis[i] << (i == n ? '\n' : ' ');
|
|
}
|
|
}
|