您的位置:首页 > 其它

AYOJ 最短路(Bellman_Ford)

2014-03-17 09:29 344 查看
算法训练 最短路

时间限制:1.0s 内存限制:256.0MB

问题描述

给定一个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
数据规模与约定

对于10%的数据,n = 2,m = 2。

对于30%的数据,n <= 5,m <= 10。

对于100%的数据,1 <= n <= 20000,1 <= m <= 200000,-10000 <= l <= 10000,保证从任意顶点都能到达其他所有顶点。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#define MAXM 200010
#define INFF 10000000
using namespace std;
int Ver, Edge;
int first[MAXM];
int d[MAXM], u[MAXM], v[MAXM], w[MAXM], nextE[MAXM];
void read_graph()
{
scanf("%d%d", &Ver, &Edge);
for(int i=1; i<=Ver; i++)first[i] = -1; //初始化表头
for(int e=1; e<=Edge; e++){
scanf("%d%d%d", &u[e], &v[e], &w[e]);
nextE[e] = first[u[e]];              //插入链表
first[u[e]] = e;
}
return ;
}
void Bellman_Ford()
{
queue<int> q;
bool inq[MAXM];
for(int i=1; i<=Ver; i++)d[i] = (i==1 ? 0 : INFF);
memset(inq, 0, sizeof(inq));//“在队列中的”标志
q.push(1);
while(! q.empty())
{
int x = q.front(); q.pop();
inq[x] = false;             //清除"在队列中的"标志
for(int e=first[x]; e!=-1; e=nextE[e])
if(d[v[e]] > d[x] + w[e])
{
d[v[e]] = d[x] + w[e];
if(!inq[v[e]])//如果已经在队列中,就不要重复加了
{
inq[v[e]] = true;
q.push(v[e]);
}
}
}
for(int i=2; i<=Ver; i++){
cout<<d[i]<<endl;
}
return ;
}
int main()
{
read_graph();
Bellman_Ford();
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: