Codeforces 459E 图上DP 解题报告

本文介绍了一种解决特定图论问题的方法,即在一个加权有向图中寻找边权重递增且边数最多的路径。通过将所有边按权重排序,并使用动态规划技巧,实现了高效的求解算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

E. Pashmak and Graph

Pashmak’s homework is a problem about graphs. Although he always tries to do his homework completely, he can’t solve this problem. As you know, he’s really weak at graph theory; so try to help him in solving the problem.
You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.
Help Pashmak, print the number of edges in the required path.

Input

The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there’s a directed edge with weight wi from vertex ui to vertex vi.
It’s guaranteed that the graph doesn’t contain self-loops and multiple edges.

Output

Print a single integer — the answer to the problem.

Examples

input
3 3
1 2 1
2 3 1
3 1 1
output
1
input
3 3
1 2 1
2 3 2
3 1 3
output
3
input
6 7
1 2 1
3 2 5
2 4 2
2 5 2
2 6 9
5 4 3
4 3 4
output
6

【解题报告】

定义dp[i]表示第i条边结尾的情况下的最长路径。f[i]表示点i结尾的情况的最长路径。
对所有的边进行排序,那么前面的边只可能小于等于后面的边。
所以dp[i] = f[e[i].u]+1
很明显f[e[j].v] = max(f[e[j].v], dp[j])

代码如下:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define N 300010
#define inf 0x3f3f3f3f

int n,m;
int dp[N],f[N];
struct Edge
{
    int u,v,w;
    bool friend operator < (Edge a,Edge b)
    {return a.w<b.w;}
}e[N];

int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;++i)
        scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
    sort(e+1,e+m+1);
    int tmp=1,ans=-inf;
    for(int i=1;i<=m;++i)
    {
        dp[i]=f[e[i].u]+1;
        if(i==m||e[i].w!=e[i+1].w)
        {
            for(int j=tmp;j<=i;++j)
                f[e[j].v]=max(f[e[j].v],dp[j]);
            tmp=i+1;
        }
        ans=max(ans,dp[i]);
    }
    printf("%d\n",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值