题目描述

设G为有n个顶点的有向无环图,G中各顶点的编号为1到n,且当为G中的一条边时有i < j。设w(i,j)为边的长度,请设计算法,计算图G中<1,n>间的最长路径。

输入格式

输入文件longest.in的第一行有两个整数n和m,表示有n个顶点和m条边,接下来m行中每行输入3个整数a,b,v(表示从a点到b点有条边,边的长度为v)。

输出格式

输出文件longest.out,一个整数,即1到n之间的最长路径.如果1到n之间没连通,输出-1。


拓扑排序求最长路

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
const int N=1e3+5e2+11,M=5e4+10;
int in[N],maxn[M],bj[M];
int Next[M],head[N],go[M],w[M],tot;
inline void add(int u,int v,int o){
Next[++tot]=head[u];head[u]=tot;go[tot]=v;w[tot]=o;
}
int n,m;
void TopSort()
{
queue<int>q;
for(int i=1;i<=n;i++)
if(in[i]==0)q.push(i);
while(q.size()){
int u=q.front();
q.pop();
for(int i=head[u];i;i=Next[i]){
int y=go[i];
in[y]--;
if(bj[u]==1){
if(maxn[y]<maxn[u]+w[i])
maxn[y]=maxn[u]+w[i];
bj[y]=1;
}
if(in[y]==0)q.push(y);
}
}
}
int main(){ cin>>n>>m;
for(int i=1,u,v,o;i<=m;i++){
scanf("%d%d%d",&u,&v,&o);
add(u,v,o);in[v]++; }
maxn[n]=-1;bj[1]=1;
TopSort();
cout<<maxn[n]<<endl;
return 0;
}

spfa求最长路

#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=2510,M=5e5+10,inf=1<<30;
int nxt[M],head[N],go[M],w[M],tot;
inline void add(int u,int v,int o){
nxt[++tot]=head[u];head[u]=tot;go[tot]=v;w[tot]=o;
}
int n,m,dis[N];
bool vis[N];
queue<int>q;
inline void dj(){
memset(dis,0xcf,sizeof(dis)); q.push(1); dis[1]=0;
while(q.size()){
int u=q.front(); vis[u]=0; q.pop();
for(int i=head[u];i;i=nxt[i]){
int v=go[i];
if(dis[v]<dis[u]+w[i]){
dis[v]=dis[u]+w[i];
if(!vis[v])q.push(v),vis[v]=1;
}
}
}
}
signed main(){
cin>>n>>m;
for(int i=1,u,v,o;i<=m;i++){
scanf("%d%d%d",&u,&v,&o);
add(u,v,o);
}
dj();
if(dis[n]>=0)cout<<dis[n]<<endl;
else cout<<-1<<endl;
}

最新文章

  1. 高性能Java网络框架 MINA
  2. 伪Acmer的推理(dfs/bfs)
  3. solr导入数据库数据-tinyint数据转boolean
  4. [学习笔记]ESXI学习记录
  5. ios 开发之 Xcode6 No valid signing identities (i.e. certificate and private key pair) matching...
  6. crawler
  7. Android(java)学习笔记128:使用proguard混淆android代码
  8. ASP.NET - 编写让别人能读懂的代码
  9. java之jvm学习笔记二(类装载器的体系结构)
  10. C/C++知识点清单02-上
  11. nginx正则匹配
  12. 自学Aruba之添加黑名单Blacklists方法
  13. 6——ThinkPhp中的请求:
  14. linux 卸载自带apache httpd 安装apache httpd
  15. 20145326蔡馨熤《网络对抗》——MSF基础应用
  16. Python: json模块实例详解
  17. IDEA 不能显示项目里的文件结构
  18. x64免签名驱动程序
  19. 【驱动笔记11】使用DeviceIoControl通信
  20. Oracle数据类型之nchar

热门文章

  1. I/O流操作
  2. Magicodes.Pay,打造开箱即用的统一支付库,已提供ABP模块封装
  3. 创建一个线程池(java)
  4. 用这个库 3 分钟实现让你满意的表格功能:Bootstrap-Table
  5. Lab8:文件系统
  6. 多线程编程(3)——synchronized原理以及使用
  7. RALM: 实时 Look-alike 算法在微信看一看中的应用
  8. 使用boost data_time模块来获取毫秒级时间并转换为string字符串
  9. 扛把子组作业要求 20191024-3 互评Alpha阶段作品
  10. PL真有意思(五):数据类型