蓝桥杯 最短路 spfa

来源:互联网 发布:ubuntu ftp 上传权限 编辑:程序博客网 时间:2024/06/17 14:00
问题描述

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


直接套用spfa模板  点我看原题

#include<iostream>#include<cstdio>#include<cstring> #include<vector>#include<queue>using namespace std;const int mx = 2e4 + 10; int vis[mx], dis[mx], n, m;struct node{int to, w;};vector<node> ve[mx];queue <int>q;void spfa(){memset(dis, 63, sizeof (dis));memset(vis, 0, sizeof(vis));while(!q.empty()) q.pop();dis[1] = 0;q.push(1);vis[1] = 1;while(!q.empty()){int x = q.front();q.pop();vis[x] = 0;for(int i = 0; i < ve[x].size(); i++){  //忘了写括号  node te= ve[x][i];if(dis[x] + te.w < dis[te.to]){dis[te.to] = dis[x] + te.w;if(!vis[te.to]){vis[te.to] = 1;q.push(te.to);}}}}for(int i = 2; i <= n; i++) printf("%d\n", dis[i]);}int main(){while(scanf("%d%d", &n,&m) != EOF){int u, v ,w;node te;while(m--){scanf("%d%d%d",&u, &v, &w);te.to = v; te.w =w;ve[u].push_back(te);}spfa();for(int i = 1; i <= n; i++){ve[i].clear();}}return 0;}


原创粉丝点击