算法训练 最短路 (spfa算法)


Link:点击打开链接


问题描述
给定一个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,保证从任意顶点都能到达其他所有顶点。



AC code:

#include
#include
#include
#include
#include
#include
#include
#include
#define LL long long
#define EPS 1e-9
#define MAXN 200010
#define INF 9999999999
using namespace std;
struct node{
	int u,v,w;
	int next;
}E[MAXN];
bool hash[MAXN];
int head[MAXN];
LL dis[MAXN];//结果 
int tot,n,m;//n点个数  m边条数  
void init()
{
    memset(head,-1,sizeof(head));
	tot=0;
}
void ins(int uu,int vv,int ww)//前向星 
{
	E[tot].u=uu;
	E[tot].v=vv;
	E[tot].w=ww;
	E[tot].next=head[uu];
	head[uu]=tot++;
}
bool spfa(int s,int n)//s为源点 
{
	queueque;
	int count[MAXN];
//	memset(dis,INF,sizeof(dis);wa
//	memset(hash,false,sizeof(hash));wa
//	memset(count,0,sizeof(count));wa
	for(int i=0;i<=n;i++)//切记:不能直接用上面的memset,必須确定范围,否则结果wa!!! 
	{
		dis[i]=INF;
		hash[i]=false;
		count[i]=0;
	}
	dis[s]=0;
	que.push(s);
	hash[s]=true;
	count[s]=1;
	while(!que.empty())
	{
		int u=que.front();
		que.pop();
		hash[u]=false;
		if(count[u]>n)//存在负环 
			return false;
		for(int i=head[u];i!=-1;i=E[i].next)
		{
			int v=E[i].v;
			if(dis[v]>dis[u]+E[i].w)
			{
				dis[v]=dis[u]+E[i].w;
				if(!hash[v])
				{
					que.push(v);
					hash[v]=true;
					count[v]++;
				}
			}
		}
	}
	return true;
 } 
int main()
{
	int u,v,w;
	while(cin>>n>>m)
	{
		init();
		for(int i=1;i<=m;i++)
		{
			cin>>u>>v>>w;
			ins(u,v,w);
		}
		spfa(1,n);
		for(int i=2;i<=n;i++)
		{
			cout<



你可能感兴趣的:(ACM,BFS,图论,搜索,贪心)