拓扑排序O(E), bellman O(VE)   , 使用邻接表的dfs O(V+E) ,floyd O(N*N*N)

 

bellman算法只能判断是否存在负环。

所以可以先把权值全部设为-1

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <vector>
 4 #include <stack>
 5 using namespace std;
 6 const int N = 10000 + 10;
 7 const int INF = 1<<30;
 8 struct node
 9 {
10     int u,v,weight;
11 }g[N+N];
12 int dist[N];
13 inline int max(const int &a, const int &b)
14 {
15     return a < b ? b : a;
16 }
17 
18 void init(int n)
19 {
20     for(int i=0; i<=n; ++i)
21     {
22     
23         dist[i] = INF;
24     }
25 }
26 
27 void relax(int u, int v, int weight)
28 {
29     if(dist[v]  > dist[u] + weight)
30         dist[v] = dist[u] + weight;    
31 }
32 bool bell(int n, int m)
33 {
34     int i,j;
35     for(i=1; i<n; ++i)
36         for(j=0; j<m; ++j)
37             relax(g[j].u,g[j].v,g[j].weight);
38     
39     for(i=0; i<m; ++i)
40         if(dist[g[i].v] > dist[g[i].u] +g[i].weight)
41             return true;
42     return false;
43 }
44 int main()
45 {
46     int n,m,i,u,v;
47     while(scanf("%d%d",&n,&m)!=EOF)
48     {
49         if(n==0 && m==0)
50             break;
51         init(n);
52         for(i=0; i<m; ++i)
53         {
54             scanf("%d%d",&g[i].u,&g[i].v);
55             g[i].weight = -1;//把权值全部改为负的,然后判断是不是存在负环
56             if(g[i].u==0)
57                 dist[g[i].v] = -1;
58         }
59         if(bell(n,m))
60             puts("NO");
61         else
62             puts("YES");
63     }
64 }
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-16
  • 2021-12-02
  • 2021-09-29
  • 2022-03-01
  • 2022-03-10
猜你喜欢
  • 2022-12-23
  • 2021-11-03
  • 2022-01-17
  • 2021-06-09
  • 2022-01-26
  • 2022-12-23
  • 2021-12-20
相关资源
相似解决方案