Stay Hungry,Stay Foolish!

G - Longest Path -- 拓扑序 + DP

G - Longest Path

https://atcoder.jp/contests/dp/tasks/dp_g

 

思路

使用拓扑序, 依此从入度为0的节点开始, 向外扩展,直至只剩一个节点

扩展的过程中,对每个点的最大路径做记录。

 

Code

https://atcoder.jp/contests/dp/submissions/3936985

#include<cstdio>
#include<algorithm>
#include<vector>
#define N_ 101000
using namespace std;
int Deg[N_], Q[N_], head, tail, n, m, D[N_];
vector<int>E[N_];
int main() {
    int i, a, b;
    scanf("%d%d", &n,&m);
    for (i = 0; i < m; i++) {
        scanf("%d%d", &a, &b);
        E[a].push_back(b);
        Deg[b]++;
    }
    for (i = 1; i <= n; i++) {
        if (!Deg[i])Q[++tail] = i;
    }
    int res = 0;
    while (head < tail) {
        int x = Q[++head];
        res = max(res, D[x]);
        for (auto &y : E[x]) {
            Deg[y]--;
            D[y] = max(D[y], D[x] + 1);
            if (!Deg[y])Q[++tail] = y;
        }
    }
    printf("%d\n", res);
}

 

posted @ 2023-02-27 21:53  lightsong  阅读(19)  评论(0编辑  收藏  举报
Life Is Short, We Need Ship To Travel