zoukankan      html  css  js  c++  java
  • AYOJ 最短路(Bellman_Ford)

      算法训练 最短路  

    时间限制:1.0s   内存限制:256.0MB
     
    问题描述

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

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 #include<queue>
     5 #define MAXM 200010
     6 #define INFF 10000000
     7 using namespace std;
     8 int Ver, Edge;
     9 int first[MAXM];
    10 int d[MAXM], u[MAXM], v[MAXM], w[MAXM], nextE[MAXM];
    11 void read_graph()
    12 {
    13     scanf("%d%d", &Ver, &Edge);
    14     for(int i=1; i<=Ver; i++)first[i] = -1; //初始化表头
    15     for(int e=1; e<=Edge; e++){
    16         scanf("%d%d%d", &u[e], &v[e], &w[e]);
    17         nextE[e] = first[u[e]];              //插入链表
    18         first[u[e]] = e;
    19     }
    20     return ;
    21 }
    22 void Bellman_Ford()
    23 {
    24     queue<int> q;
    25     bool inq[MAXM];
    26     for(int i=1; i<=Ver; i++)d[i] = (i==1 ? 0 : INFF);
    27     memset(inq, 0, sizeof(inq));//“在队列中的”标志
    28     q.push(1);
    29     while(! q.empty())
    30     {
    31         int x = q.front(); q.pop();
    32         inq[x] = false;             //清除"在队列中的"标志
    33         for(int e=first[x]; e!=-1; e=nextE[e])
    34         if(d[v[e]] > d[x] + w[e])
    35         {
    36             d[v[e]] = d[x] + w[e];
    37             if(!inq[v[e]])//如果已经在队列中,就不要重复加了
    38             {
    39                 inq[v[e]] = true;
    40                 q.push(v[e]);
    41             }
    42         }
    43     }
    44     for(int i=2; i<=Ver; i++){
    45         cout<<d[i]<<endl;
    46     }
    47     return ;
    48 }
    49 int main()
    50 {
    51     read_graph();
    52     Bellman_Ford();
    53     return 0;
    54 }
    View Code
  • 相关阅读:
    thread.md
    Linux系统编程手册_第6章_进程
    第一章.md
    开始.md
    粘滞位
    端口转发和端口映射
    virtualbox.md
    第6章.md
    JsparentNode、parentElement,childNodes、children 它们有什么区别呢?
    Sql注入防小试
  • 原文地址:https://www.cnblogs.com/qiu520/p/3604454.html
Copyright © 2011-2022 走看看