洛谷 P3371 【模板】单源最短路径(弱化版) && dijkstra模板
2024-09-04 13:52:32
嗯...
题目链接:https://www.luogu.org/problem/P3371
没什么好说的,这是一个最短路的模板,这里用的dijkstra做的...
注意:
1.dijkstra和邻接表一块有点别扭,但还是可以遍历的...
2.dis数组不能初始化为2147483647,而要初始化0x3f3f,最后判一下还是不是0x3f3f即可
AC代码:
#include<cstdio>
#include<cstring>
#include<iostream> using namespace std;
const int maxn = ;
int n, m, tot, s;
long long inf = 0x3f3f;
int vis[maxn], dis[maxn], e[maxn];
// vis -> 是否被访问过 dis -> 最短路 e -> 边的编号
struct node{
int next, to, from, val;
} g[maxn]; inline void add(int u, int v, int w){
g[++tot].from = u;
g[tot].next = e[u];
e[u] = tot;
g[tot].to = v;
g[tot].val = w;
}//邻接表 inline void dijkstra(int x){
memset(vis, , sizeof(vis));
for(int i = ; i <= n; i++) dis[i] = (i == x ? : inf);//初始化
for(int i = ; i <= n; i++){
int t = , y = inf;
for(int j = ; j <= n; j++) if(!vis[j] && dis[j] <= y) y = dis[t = j];
vis[t] = ;
for(int j = e[t]; j; j = g[j].next) dis[g[j].to] = min(dis[g[j].to], dis[t] + g[j].val);
}//松弛操作
for(int i = ; i <= n; i++) {if(dis[i] == 0x3f3f) printf("2147483647 "); else printf("%d ", dis[i]);}
} int main(){
memset(dis, 0x3f3f, sizeof(dis));
scanf("%d%d%d", &n, &m, &s);
for(int i = ; i <= m; i++){
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
add(u, v, w);//单向图
}
dijkstra(s);
return ;
}
AC代码
最新文章
- C#GDI+图像处理
- ACM Binary String Matching
- ASP.NET MVC 4下 Code First 数据库迁移
- Navicat(连接) -1之Navicat Cloud
- Mapped Statements collection does not contain value for TaskMapper.selectByPrimaryKey
- hdu 1034 Candy Sharing Game
- 国内流行的两大开源.net微信公众平台SDK对比分析
- javascript在一个字符串中每隔多少字符插入某个字符串
- 在一个RAC集群中最多支持多少节点
- leetcode 生成杨辉三角形, 118 119 Pascal&#39;s Triangle 1,2
- XamarinForm Effects 调用事件
- JS 设计模式一 -- 原型模式
- 如何让多个li居中于ul中间
- PTA——数组平移
- C#开发微信支付之企业向用户付款
- CF 1041 1042整理
- socket 编程中。 服务端用到多线程
- .net 程序加密
- Spring Security 中的加密BCryptPasswordEncoder
- grep和egrep正则表达式