[Codeforces Round #261 (Div. 2) E]Pashmak and Graph(Dp)

本文介绍了一道关于寻找带权有向图中边权严格递增的最长路径的问题,并提供了一个O(mlogm)复杂度的解决方案。该方案通过先对边按权重排序,再动态规划求解每个节点作为路径终点时的最长递增路径。

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

Description

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.

Solution

题意:给出一个无自环、重边的带权有向图,求边权严格递增的最长的路径(可以是非简单路径)

思路题QAQ

O(mlogm)以边权排序后再逐个处理,这样就保证了递增,然后可以O(m)求解,维护每个点作为结尾的最长的边权上升路径的长度

注意边权相等的情况要放在一起处理

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#define MAXN 300010
using namespace std;
int n,m,f[MAXN],g[MAXN];
struct Node
{
    int u,v,w;
    bool operator < (const Node& x) const
    {return w<x.w;}
}Edges[MAXN];
int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        memset(f,0,sizeof(f));
        memset(g,0,sizeof(g));
        for(int i=1;i<=m;i++)
        scanf("%d%d%d",&Edges[i].u,&Edges[i].v,&Edges[i].w);
        int t=1,res=0;
        sort(Edges+1,Edges+1+m);
        for(int i=1;i<=m;i++)
        {
            f[i]=g[Edges[i].u];
            
            if(Edges[i].w!=Edges[i+1].w)
            {
                for(int j=t;j<=i;j++)
                g[Edges[j].v]=max(g[Edges[j].v],f[j]+1),res=max(res,g[Edges[j].v]);
                t=i+1;
            }
        }
        printf("%d\n",res);
    }
    return 0;
} 

 

转载于:https://www.cnblogs.com/Zars19/p/6917791.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值