Luogu1137 旅行计划 (拓扑排序)

拓扑排序与动态规划
本文介绍了一种结合拓扑排序与动态规划的算法实现,通过记录节点的入度并利用队列进行节点处理的方式,实现了对有向无环图中最长路径的有效计算。

每次入队时DP : \(f[v] = \max \{f[u] + 1\}\)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define R(a,b,c) for(register int  a = (b); a <= (c); ++ a)
#define nR(a,b,c) for(register int  a = (b); a >= (c); -- a)
#define Max(a,b) ((a) > (b) ? (a) : (b))
#define Min(a,b) ((a) < (b) ? (a) : (b))
#define Fill(a,b) memset(a, b, sizeof(a))
#define Abs(a) ((a) < 0 ? -(a) : (a))
#define Swap(a,b) a^=b^=a^=b
#define ll long long

//#define ON_DEBUG

#ifdef ON_DEBUG

#define D_e_Line printf("\n\n----------\n\n")
#define D_e(x)  cout << #x << " = " << x << endl
#define Pause() system("pause")
#define FileOpen() freopen("in.txt","r",stdin);

#else

#define D_e_Line ;
#define D_e(x)  ;
#define Pause() ;
#define FileOpen() ;

#endif

struct ios{
    template<typename ATP>ios& operator >> (ATP &x){
        x = 0; int f = 1; char c;
        for(c = getchar(); c < '0' || c > '9'; c = getchar()) if(c == '-')  f = -1;
        while(c >= '0' && c <= '9') x = x * 10 + (c ^ '0'), c = getchar();
        x*= f;
        return *this;
    }
}io;
using namespace std;

const int N = 100007;

struct Edge{
    int nxt, pre;
}e[N << 1];
int head[N], cntEdge;
inline void add(int u, int v){
    e[++cntEdge] = (Edge){ head[u], v}, head[u] = cntEdge;
}

int ans[N];
int in[N];
int q[N], top;
int main(){
    FileOpen();
    
    int n, m;
    io >> n >> m;
    R(i,1,m){
        int u, v;
        io >> u >> v;
        add(u, v);
        ++in[v];
    }
    
    R(i,1,n){
        if(!in[i]){
            ans[i] = 1;
            q[++top] = i;   
        }
        
    }
    while(top){
        int u = q[top--];
        for(register int i = head[u]; i; i = e[i].nxt){
            int v = e[i].pre;
            --in[v];
            ans[v] = Max(ans[v], ans[u] + 1);
            if(!in[v]){
                q[++top] = v;
            }
        }
    }
    
    R(i,1,n){
        printf("%d\n", ans[i]);
    }
    
    return 0;
}

1570282-20190723093603885-1964549588.png

转载于:https://www.cnblogs.com/bingoyes/p/11229586.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值