您的位置:首页 > 其它

POJ 3259 Wormholes SPFA 判断负环

2017-07-07 09:38 423 查看
题目链接: POJ—3259 Wormholes

题目大意: 给一个图,求有没有负环。

题目分析:第一次用SPFA(代码在后面)





AC 代码(写的丑,勿喷)(bellmen-ford应该也可以的)

/***********************************
Problem: 3259       User: ChenyangDu
Memory: 280K        Time: 141MS
Language: C++       Result: Accepted
************************************/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>

using namespace std;

const int maxn = 505,INF = 10000000;
int T,n,m,d[maxn],times[maxn];

struct edge{int to,w;};

vector <edge> G[maxn];

edge Edge(int to,int w){
edge t;
t.to = to;
t.w = w;
return t;
}

void add_edge(int s,int e,int w){
for(int i=0;i<G[s].size();i++){
if(G[s][i].to == e){//判断重边
G[s][i].w = min(G[s][i].w,w);
retur
4000
n;
}
}
G[s].push_back(Edge(e,w));
}

int main(){
//freopen("in.txt","r",stdin);
scanf("%d",&T);
while(T--){
int w;
bool n_loop = false;
scanf("%d%d%d",&n,&m,&w);
for(int i=1;i<=n;i++){
G[i].resize(0);
d[i] = INF;
}
memset(times,0,sizeof(times));
for(int s,e,t,i=1;i<=m;i++){
scanf("%d%d%d",&s,&e,&t);
add_edge(s,e,t);
add_edge(e,s,t);
}
for(int s,e,t,i=1;i<=w;i++){
scanf("%d%d%d",&s,&e,&t);
add_edge(s,e,-t);
}
//以下是SPFA
queue<int>que;
que.push(1);
d[1] = 0;
while(!que.empty()){
int t = que.front();que.pop();
for(int i=0;i<G[t].size();i++){
int v = G[t][i].to;
if(d[v] > d[t] + G[t][i].w){
d[v] = d[t] + G[t][i].w;
times[v] ++;
if(times[v] > 1000){//出现负环
n_loop = true;
goto next;
}
que.push(v);
}
}
}
next:

if(n_loop)printf("YES\n");
else printf("NO\n");
}
fclose(stdin);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poj SPFA 负环