nyoj 天下第一 (spfa)

要求路径长度大于一,判断出环即可结束。。

 

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstdlib>
 4 #include<cstring>
 5 #include<string>
 6 #include<queue>
 7 #include<algorithm>
 8 #include<map>
 9 #include<iomanip>
10 #include<climits>
11 #include<string.h>
12 #include<cmath>
13 #include<stdlib.h>
14 #include<vector>
15 #include<set>
16 #define INF 1e7
17 #define MAXN 100010
18 #define maxn 1000010
19 #define Mod 1000007
20 #define N 1010
21 using namespace std;
22 typedef long long LL;
23 
24 struct node{ int x; double w; };
25 vector<node> G[1010];
26 int u, v;
27 double w;
28 int n, m;
29 int T;
30 int cnt[555];
31 int vis[555];
32 double dis[555];
33 
34 bool  spfa()
35 {
36     queue<node> q;
37     q.push({ 1, 0 });
38     vis[1] = 1;
39     dis[1] = 1;
40     while (!q.empty()){
41         node now = q.front();
42         q.pop();
43         vis[now.x] = 0;
44         for (int i = 0; i < G[now.x].size(); ++i) {
45             node v = G[now.x][i];
46             if (dis[now.x] * v.w > dis[v.x]) {
47                 dis[v.x] = dis[now.x] * v.w;
48                 if (!vis[v.x]) {
49                     vis[v.x] = 1;
50                     cnt[v.x]++;
51                     q.push({ v.x, dis[v.x] });
52                     if (cnt[v.x] >= n) return true;
53                 }
54             }
55         }
56     }
57     return false;
58 }
59 
60 void init()
61 {
62     memset(dis,0,sizeof(dis));
63     memset(vis,0,sizeof(vis));
64     memset(cnt,0,sizeof(cnt));
65     for (int i = 0; i <= n; ++i)
66         G[i].clear();
67 }
68 
69 void run()
70 {
71     cin >> n >> m;
72     init();
73     for (int i = 0; i < m; ++i) {
74         cin >> u >> w >> v;
75         G[u].push_back({v,w});
76     }
77     if (spfa()) puts("Yes");
78     else puts("No");
79 }
80 
81 int main()
82 {
83     cin >> T;
84     while (T--)
85         run();
86     //system("pause");
87     return 0;
88 }

 

posted @ 2015-03-14 11:26  UsedRose  阅读(119)  评论(0编辑  收藏  举报