您的位置:首页 > 其它

POJ3259 Wormholes

2013-05-14 01:25 162 查看
微微发亮的传送门

spfa求负环,如果某一个节点入队列N次,那么可以负环存在,否则不存在

#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;
const int maxn = 555;
int dist[maxn], cnt[maxn], n, m, w;
bool inque[maxn];
vector<pair<int, int> > g[maxn];
void add(int x, int y, int z){
g[x].push_back(make_pair(y, z));
}
bool spfa(int x){
queue<int> que;
memset(dist, 63, sizeof(dist));
dist[x] = 0;
que.push(x);
inque[x] = 1;
while(!que.empty()){
int u = que.front();
que.pop();
inque[u] = 0;
for (int i = 0; i < g[u].size(); i++)
if (dist[g[u][i].first] > dist[u] + g[u][i].second){
dist[g[u][i].first] = dist[u] + g[u][i].second;
if (!inque[g[u][i].first]){
inque[g[u][i].first] = 1;
que.push(g[u][i].first);
cnt[g[u][i].first] += 1;
if (cnt[g[u][i].first] >= n) return 1;
}
}
}
return 0;
}
int main(){
int cs;
scanf("%d", &cs);
while(cs--){
for (int i = 0; i < maxn; i++) g[i].clear();
scanf("%d%d%d", &n, &m, &w);
int x, y, z;
while(m--){
scanf("%d%d%d", &x, &y, &z);
add(x, y, z);
add(y, x, z);
}
while(w--){
scanf("%d%d%d", &x, &y, &z);
add(x, y, -z);
}
bool f = 0;
for (int i = 0; i < n; i++){
memset(inque, 0, sizeof(inque));
memset(cnt, 0, sizeof(cnt));
if (spfa(i)){
f = 1; break;
}
}
if (f) printf("YES\n");
else printf("NO\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: