关于拓扑排序的一个小问题
  • 板块灌水区
  • 楼主yyz38
  • 当前回复3
  • 已保存回复3
  • 发布时间2024/3/15 21:38
  • 上次更新2024/3/16 08:35:46
查看原帖
关于拓扑排序的一个小问题
1122958
yyz38楼主2024/3/15 21:38

负环这道题大家都知道。 但如果用拓扑排序做这道题只能拿20分,其他的都是WA 蒟蒻的小代码:``` #include<bits/stdc++.h> using namespace std;

const int MAXN = 2005; int n, m; vector<pair<int, int>> edges[MAXN]; int inDegree[MAXN]; bool negativeCycle;

void topologicalSort() { queue q; for (int i = 1; i <= n; i++) { if (inDegree[i] == 0) { q.push(i); } }

while (!q.empty()) {
    int u = q.front();
    q.pop();

    for (auto edge : edges[u]) {
        int v = edge.first;
        int w = edge.second;
        inDegree[v]--;
        if (inDegree[v] == 0) {
            q.push(v);
        }
    }
}

}

int main() { int T; cin >> T; while (T--) { cin >> n >> m; for (int i = 1; i <= n; i++) { edges[i].clear(); inDegree[i] = 0; } negativeCycle = false;

    for (int i = 0; i < m; i++) {
        int u, v, w;
        cin >> u >> v >> w;
        edges[u].push_back({v, w});
        inDegree[v]++;
    }

    topologicalSort();

    for (int i = 1; i <= n; i++) {
        for (auto edge : edges[i]) {
            int v = edge.first;
            int w = edge.second;
            if (w < 0) {
                negativeCycle = true;
                break;
            }
        }
        if (negativeCycle) {
            break;
        }
    }

    if (negativeCycle) {
        cout << "YES" << endl;
    } else {
        cout << "NO" << endl;
    }
}
return 0;

}

有没有大佬能解释一下
2024/3/15 21:38
加载中...