• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
magicat
博客园    首页    新随笔    联系   管理    订阅  订阅
P1807 最长路

P1807 最长路

在DAG上拓扑排序dp,题目数据没有环

分析:   f[v]=max(f[v],f[u]+value[u][i];

#include<iostream>
#include<cstring>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;


const int mod=80112002;
vector<int> son[100010],value[100010];
int in[100010],out[100010];
long long f[100010],ans=0;
int n,m;
void bfs()
{ 
    queue<int> q;
    for(int i=1;i<=n;i++)   
    {
        f[i]=-1e9;
        if(in[i]==0)
            q.push(i);
    }
    f[1]=0;
    while(!q.empty())
    {
        int u=q.front();q.pop();
        //cout<<u<<" ";
        int len=son[u].size();
        for(int i=0;i<len;i++)
        {
            int v=son[u][i];
            f[v]=max(f[v],f[u]+value[u][i]);
            if(--in[v]==0)
            {
                q.push(v);
            }
        }
    }
    if(f[n]!=-1e9)cout<<f[n]<<endl;
    else cout<<-1<<endl;
}

int main()
{
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        int x,y,z;    cin>>x>>y>>z;
        son[x].push_back(y);
        value[x].push_back(z);
        in[y]++,out[x]++;
    }
    bfs();
    return 0;
}

 

本文来自博客园,作者:magicat,转载请注明原文链接:https://www.cnblogs.com/magicat/p/16535223.html

posted on 2022-07-30 16:14  magicat  阅读(21)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3