• 利用Bellman-Ford算法(有向图) 判断负环


      1 // 根据Bellman-Ford算法的原理
      2 // 判断负环(算法的最大更新次数,应该是顶点数-1次)
      3 // 而如果存在负环,算法会一直更新下去
      4 
      5 // 我们根据循环进行的次数,来判断负环
      6 
      7 #include <iostream>
      8 #include <cstdio>
      9 #include <cstring>
     10 
     11 using namespace std;
     12 
     13 const int max_N=1000+2;
     14 const int max_E=10000+2;
     15 
     16 int N,E;
     17 
     18 struct edge
     19 {
     20     int from,to,cost;
     21 };
     22 edge es[max_E];
     23 
     24 int d[max_N];
     25 
     26 void solve()
     27 {
     28     memset(d,0,sizeof(d));
     29     int cnt=0;
     30     while(cnt<N)
     31     {
     32         bool update=false;
     33         for(int i=0;i<E;++i)
     34         {
     35             edge e=es[i];
     36             if(d[e.to]>d[e.from]+e.cost)
     37             {
     38                 printf("hei  ");
     39                 d[e.to]=d[e.from]+e.cost;
     40                 update=true;
     41             }
     42         }
     43         if(update==false)
     44         {
     45             printf("NO
    ");
     46             break;
     47         }
     48         else
     49         {
     50             ++cnt;
     51             if(cnt==N)
     52             {
     53                 printf("YES
    ");
     54                 break;
     55             }
     56         }
     57     }
     58 }
     59 
     60 int main()
     61 {
     62     scanf("%d %d",&N,&E);
     63     for(int i=0;i<E;++i)
     64     {
     65         scanf("%d%d%d",&es[i].from,&es[i].to,&es[i].cost);
     66     }
     67     solve();
     68     return 0;
     69 }
     70 
     71 /*
     72 7 10
     73 0 1 2
     74 0 2 5
     75 1 2 4
     76 1 3 6
     77 1 4 10
     78 2 3 2
     79 3 5 1
     80 4 5 3
     81 4 6 5
     82 5 6 9
     83 NO
     84 */
     85 
     86 /*
     87 3 3
     88 0 1 1
     89 1 2 2
     90 2 1 -2
     91 NO
     92 */
     93 
     94 /*
     95 3 3
     96 0 1 1
     97 1 2 2
     98 2 1 -3
     99 
    100 */
  • 相关阅读:
    pip install selenium==版本号 报错
    解决phantomjs输出中文乱码
    phantomjs学习之网页访问测速
    phantomjs学习之截图
    bzoj1069-最大土地面积
    hdu4372-Count the Buildings
    bzoj3786-星系探索
    Codeforces633H-Fibonacci-ish II
    hdu3625-Rooms
    斯特林数
  • 原文地址:https://www.cnblogs.com/jishuren/p/12314001.html
Copyright © 2020-2023  润新知