问题描述
给定一个n个顶点,m条边的有向图(其中某些边权可能为负,但保证没有负环)。请你计算从1号点到其他点的最短路(顶点从1到n编号)。
输入格式
第一行两个整数n, m。
接下来的m行,每行有三个整数u, v, l,表示u到v有一条长度为l的边。
输出格式
共n-1行,第i行表示1号点到i+1号点的最短路。
样例输入
3 3
1 2 -1
2 3 -1
3 1 2
1 2 -1
2 3 -1
3 1 2
样例输出
-1
-2
-2
数据规模与约定
对于10%的数据,n = 2,m = 2。
对于30%的数据,n <= 5,m <= 10。
对于100%的数据,1 <= n <= 20000,1 <= m <= 200000,-10000 <= l <= 10000,保证从任意顶点都能到达其他所有顶点。
用spfa就能搞定
#include <iostream>
#include <stdio.h>
#include <queue>
#include <vector>
using namespace std;
const int MAX = 2000000000;
int n,m;
struct road{
int e,val;
};
struct node{
int s;
int spay;
};
vector<road>bian[20000+10];//保存路
int pay[20000+10];//spfa 花费
void work()
{
node a,b;
int i;
a.s = 1;
a.spay = 0;
for(i=1;i<=n;i++)
pay[i]=MAX;
pay[1]=0;
queue<node>q;
q.push(a);
while(!q.empty())
{
a=q.front();
q.pop();
if(a.spay>pay[a.s])continue;
for(i=0;i<bian[a.s].size();i++)
{
road rd = bian[a.s][i];
b.s=rd.e;
b.spay=a.spay+rd.val;
if(pay[b.s]>b.spay)
{
pay[b.s]=b.spay;
q.push(b);
}
}
}
}
int main()
{
scanf("%d%d",&n,&m);
int a,b,c;
road rd;
while(m--)
{
scanf("%d%d%d",&a,&b,&c);
rd.e=b;
rd.val=c;
bian[a].push_back(rd);
}
work();
for(int i=2;i<=n;i++)
printf("%d\n",pay[i]);
return 0;
}