【bfs】廉价最短路径(2013特长生 T4)
生活随笔
收集整理的這篇文章主要介紹了
【bfs】廉价最短路径(2013特长生 T4)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目大意
給你一個圖,每條邊有一個代價,讓你求0到1在最短路徑的前提下的最小代價
解題思路
bfs同時求個最代價
代碼
#include<queue> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #define ll long long #define N 200 using namespace std; int n, m, x, y, z, tot, b[N], p[N], v[N], head[N]; queue<int>d; struct rec {int to, l, next; }a[N*10]; void add(int x, int y, int z) {a[++tot].to = y;a[tot].l = z;a[tot].next = head[x];head[x] = tot;return; } void bfs() {memset(b, 127/3, sizeof(b));memset(v, 127/3, sizeof(v));b[0] = 0;v[0] = 0;p[0] = 1;d.push(0);while(!d.empty())//bfs{int h = d.front();d.pop();for (int i = head[h]; i; i = a[i].next)if (b[h] + 1 < b[a[i].to] || b[h] + 1 == b[a[i].to] && v[h] + a[i].l < v[a[i].to])//沒到過或長度一樣且代價更小{b[a[i].to] = b[h] + 1;v[a[i].to] = v[h] + a[i].l;if (!p[a[i].to]){d.push(a[i].to);p[a[i].to] = 1;}}}return; } int main() {scanf("%d%d", &n, &m);for (int i = 1; i <= m; ++i){scanf("%d%d%d", &x, &y, &z);add(x, y, z);}bfs();printf("%d", v[1]);return 0; }總結
以上是生活随笔為你收集整理的【bfs】廉价最短路径(2013特长生 T4)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【dfs】栅栏的木料(2012特长生 T
- 下一篇: UglifyJS中文文档