【luogu P1137 旅行计划】 题解

题目链接:https://www.luogu.org/problemnew/show/P1137
topsort + DP

#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 100001;
struct edge{
    int next, from, to;
}e[maxn<<2];
int head[maxn], cnt, indrg[maxn], f[maxn], n, m;
queue<int> q;
void add(int u, int v)
{
    e[++cnt].to = v;
    e[cnt].next = head[u];
    head[u] = cnt;
}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i = 1; i <= m; i++)
    {
        int u,v;
        scanf("%d%d",&u,&v);
        add(u,v);
        indrg[v]++;
    }
    for(int i = 1; i <= n; i++)
    if(indrg[i] == 0)
    {
        f[i] = 1;
        q.push(i);
    }

    while(!q.empty())
    {
        int now = q.front(); q.pop();
        for(int i = head[now]; i; i = e[i].next)
        {
            f[e[i].to] = max(f[e[i].to], f[now]+1);
            if(--indrg[e[i].to] == 0) q.push(e[i].to);  
        }
    }
    for(int i = 1; i <= n; i++)
    printf("%d\n",f[i]);
    return 0;
}
posted @ 2018-06-22 11:34  Misaka_Azusa  阅读(155)  评论(0编辑  收藏  举报
Live2D