• 最短路径之Bellman-Ford算法


    第一行为源点个数,边的个数m

    接下来m行为a->b和权值

    5 5
    2 3 2
    1 2 -3
    1 5 5
    4 5 2
    3 4 3

    Bellman-Ford算法(1):

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<algorithm>
     4 #define inf 1000000000
     5 using namespace std;
     6 int main()
     7 {
     8     int dis[100], u[100], v[100], w[100];
     9     int n, m;
    10     cin >> n >> m;
    11     for (int i = 1; i <= m; i++)
    12         cin >> u[i] >> v[i] >> w[i];
    13     for (int i = 1; i <= n; i++)
    14         dis[i] = inf;
    15     dis[1] = 0;
    16     for (int k = 1; k < n; k++)
    17         for (int i = 1; i <= m; i++)
    18             dis[v[i]] = min(dis[v[i]], dis[u[i]] + w[i]);
    19     for (int i = 1; i <= n; i++)
    20         cout << dis[i] << " ";
    21     return 0;
    22 }

     (2)

     1 #include<iostream>
     2 #include<queue>
     3 #include<algorithm>
     4 using namespace std;
     5 #define inf 1000000000
     6 struct  edge
     7 {
     8     int from, to, cost;
     9 };
    10 edge es[10000];
    11 int d[100], V, E;
    12 void path(int s)
    13 {
    14     for (int i = 0; i <= V; i++) d[i] = inf;
    15     d[s] = 0;
    16     while (true)    
    17     {
    18         bool update = false;
    19         for (int i = 0; i < E; i++)
    20         {
    21             edge e = es[i];
    22             if (d[e.from] != inf&& d[e.to]>d[e.from] + e.cost)
    23             {
    24                 d[e.to] = d[e.from] + e.cost;
    25                 update = true;
    26             }     
    28         }
    29         if (!update) break;
    30     }
    31     for (int i = 1; i <= V; i++)
    32         cout << d[i] << " ";
    33 }
    34 int main()
    35 {
    36     cin >> V >> E;
    37     for (int i = 0; i < E; i++)
    38     {
    39         cin >> es[i].from >> es[i].to >> es[i].cost;
    40     }
    41     path(1);
    42     return 0;
    43 }
  • 相关阅读:
    js中的投掷筛子的小游戏
    js俩习题
    python中socket理论
    python实现计时器(装饰器)
    python之正则表达式(re模块)用法总结
    python练习题之随机生成验证码
    python中模块介绍
    python中的装饰器基本理论
    python类与对象练习题扑克牌
    Java抓取网页数据
  • 原文地址:https://www.cnblogs.com/kangdong/p/8848528.html
Copyright © 2020-2023  润新知