社区讨论

玄关,求调!!(码风良好!!)

P1807最长路参与者 2已保存回复 1

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
1 条
当前快照
1 份
快照标识符
@mhju8p27
此快照首次捕获于
2025/11/04 08:36
4 个月前
此快照最后确认于
2025/11/04 08:36
4 个月前
查看原帖
CPP
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;

const int N = 50010;

int n, m;
int d[N], dist[N];
int h[N], e[N], ne[N], w[N], idx;

void add(int a, int b, int c) {
    e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}

void preprocess() {
    queue<int> q;
    // 移除所有无法从起点到达的节点(入度为0且非起点)
    for (int i = 2; i <= n; ++i) {
        if (d[i] == 0) q.push(i);
    }
    while (!q.empty()) {
        int u = q.front(); q.pop();
        for (int i = h[u]; ~i; i = ne[i]) {
            int v = e[i];
            if (--d[v] == 0 && v != 1) q.push(v);
        }
    }
}

int longestPath() {
    queue<int> q;
    memset(dist, -0x3f, sizeof dist);
    dist[1] = 0;
    q.push(1);

    while (!q.empty()) {
        int u = q.front(); q.pop();
        for (int i = h[u]; ~i; i = ne[i]) {
            int v = e[i];
            if (dist[u] + w[i] > dist[v]) {
                dist[v] = dist[u] + w[i];
            }
            if (--d[v] == 0) {
                q.push(v);
            }
        }
    }
    return dist[n];
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    memset(h, -1, sizeof h);
    cin >> n >> m;

    for (int i = 0; i < m; ++i) {
        int u, v, c;
        cin >> u >> v >> c;
        add(u, v, c);
        d[v]++;
    }

    preprocess();
    int res = longestPath();

    if (res == -0x3f3f3f3f) cout << "-1\n";
    else cout << res << "\n";

    return 0;
}

回复

1 条回复,欢迎继续交流。

正在加载回复...