1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| #include <iostream> #include <cstdio> #include <queue> #include <algorithm> #define maxn 30010 #define maxm 5010 #define INF 1000000000 using namespace std;
int n, m, s;
struct Edge { int to, next, w; } e[3 * maxn + maxm]; int c1, head[maxn]; inline void add_edge(int u, int v, int w) { e[c1].to = v; e[c1].w = w; e[c1].next = head[u]; head[u] = c1++; }
int dis[maxn]; bool vis[maxn]; queue<int> Q; void spfa(int s) { fill(vis, vis + maxn, 0); vis[s] = 1; Q.push(s); fill(dis, dis + maxn, -INF); dis[s] = 0; while (!Q.empty()) { int u = Q.front(); Q.pop(); vis[u] = 0; for (int i = head[u]; ~i; i = e[i].next) { int v = e[i].to, w = e[i].w; if (dis[v] < dis[u] + w) { dis[v] = dis[u] + w; if (vis[v]) continue; vis[v] = 1; Q.push(v); } } } }
int main() { fill(head, head + maxn, -1); ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
cin >> n >> m; s = n + 1; for (int i = 1; i <= m; ++i) { int x, y, z; cin >> x >> y >> z; add_edge(x - 1, y, z); } for (int i = 0; i <= n; ++i) { add_edge(s, i, 0); if (!i) continue; add_edge(i - 1, i, 0); add_edge(i, i - 1, -1); } spfa(s); cout << dis[n] << "\n"; return 0; }
|