56分求助
查看原帖
56分求助
220362
chenxuanting楼主2020/5/5 16:01
#include<cstdio>
#include<iostream>
using namespace std;
int n,m,k;
int inf=1<<31-1;
int dist[1505];
struct node
{
	int u;
	int v;
	int w;
}a[40005];
void bellmanford(int x)
{
	for(int i=1;i<=n;i++){
		if(i==x){
			dist[i]=0;
		}else{
			dist[i]=inf;
		}
	}
	for(int i=1;i<=n;i++){
		for(int i1=1;i1<=n;i1++){
			int u=a[i1].u;
			int v=a[i1].v;
			int w=a[i1].w;
			if(dist[u]!=inf&&dist[u]+w<dist[v]){
				dist[v]=dist[u]+w;
			}
		}
	} 
}
int main()
{
	cin>>n>>m;
	for(int i=1;i<=m;i++){
		int u,v,w;
		cin>>u>>v>>w;
		a[i]=(node){u,v,-1*w};
	}
	bellmanford(1);
	if(dist[n]==inf){
		cout<<"-1";
		return 0;
	}
	dist[n]*=-1;
	cout<<dist[n];
	return 0;
}
2020/5/5 16:01
加载中...