题目描述
设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。
输入输出样例
输入样例
2 1
1 2 1
输出样例复制
1
#include <iostream>
#include <map>
#include <iterator>
#include <algorithm>
#include <vector>
#include <queue>
#include <list>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <sstream>
#define INF 1e6
using namespace std;
const int maxn = 1510;
int g[maxn][maxn];
int du[maxn],n,m,L[maxn];
void bfs(){
queue<int>q;
memset(L,-1,sizeof L);
L[1]=0;
q.push(1);
while(!q.empty()){
int t=q.front();
q.pop();
for(int i=1;i<=n;i++)
if(g[t][i] && L[i]<L[t]+g[t][i]){
L[i]=L[t]+g[t][i];
q.push(i);
}
}
}
int main(){
int a,b,c;
cin>>n>>m;
for(int i=0;i<m;i++){
cin>>a>>b>>c;
g[a][b] = max(g[a][b],c);
}
bfs();
cout<<L[n];
}