您的位置:首页 > 其它

poj 3259 Wormholes【Bellman-Ford Vs SPFA】

2011-07-18 03:26 183 查看
http://poj.org/problem?id=3259

用Bellman-Ford和SPFA均可以判负环。。。

SPFA

【856KB 125ms】

#include<iostream>
#include<vector>
#include<map>
#include<stack>
#include<algorithm>
#include<queue>
#include<list>
#include<set>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<stdio.h>
#include<ctype.h>
#include<iomanip>
using namespace std;

#define LL long long
#define pi acos(-1)
#define N 5000
#define INF 999999999
int n,m,w;
int d
;
int cnt
;
int vis
;
struct node
{
int to,time;
};

vector<node> v
;

void init()
{
int i,j,k;
int a,b,c;
scanf("%d%d%d",&n,&m,&w);
node p;
for(i=1;i<=n;i++)
{
v[i].clear();
cnt[i]=0;
vis[i]=0;
d[i]=INF;
}
for(i=0;i<m;i++)//双向
{
scanf("%d%d%d",&a,&b,&c);
p.to=b,p.time=c;
v[a].push_back(p);
p.to=a,p.time=c;
v[b].push_back(p);

}
for(i=0;i<w;i++)//单向
{
scanf("%d%d%d",&a,&b,&c);
p.to=b,p.time=-c;
v[a].push_back(p);
}
}

bool spfa()
{
int i,j,k;
queue<int> q;
while(!q.empty())q.pop();
q.push(1);
d[1]=0;
cnt[1]=1;
vis[1]=1;
while(!q.empty())
{
int top=q.front();
q.pop();
vis[top]=0;
for(i=0;i<(int)v[top].size();i++)
{
int to=v[top][i].to;
if(d[to]>d[top]+v[top][i].time)
{
d[to]=d[top]+v[top][i].time;
if(!vis[to])
{
vis[to]=1;
cnt[to]++;
if(cnt[to]>=n)
return 1;
q.push(to);
}
}
}
}
return 0;
}

int main()
{
//   freopen("a.txt","r",stdin);
int t;
int i,j,k;
while(scanf("%d",&t)!=EOF)
{
while(t--)
{
init();
if(spfa())
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}
Bellman-Ford 【736KB 125ms】

#include<iostream>
#include<vector>
#include<map>
#include<stack>
#include<algorithm>
#include<queue>
#include<list>
#include<set>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<stdio.h>
#include<ctype.h>
#include<iomanip>
using namespace std;

#define LL long long
#define pi acos(-1)
#define N 5000
#define INF 999999999
int n,m,w;
int cnt;
int d
;
struct node
{
int a,b,time;
}e
;

bool fuck()
{
int i,j,k;
for(i=1;i<=n;i++)
d[i]=INF;
d[1]=0;
for(i=1;i<n;i++)
{
for(j=1;j<=cnt;j++)
if(d[e[j].b]>d[e[j].a]+e[j].time)
d[e[j].b]=d[e[j].a]+e[j].time;
}
for(j=1;j<=cnt;j++)
if(d[e[j].b]>d[e[j].a]+e[j].time)
return 1;
return 0;
}

void init()
{
int i,j,k;
cnt=0;
int a,b,c;
scanf("%d%d%d",&n,&m,&w);
for(i=0;i<m;i++)//双向
{
scanf("%d%d%d",&a,&b,&c);
cnt++;
e[cnt].a=a;
e[cnt].b=b;
e[cnt].time=c;
cnt++;
e[cnt].b=a;
e[cnt].a=b;
e[cnt].time=c;
}
for(i=0;i<w;i++)//单向
{
scanf("%d%d%d",&a,&b,&c);
cnt++;
e[cnt].a=a;
e[cnt].b=b;
e[cnt].time=c*(-1);
}
}
int main()
{
//  freopen("a.txt","r",stdin);
int t;
int i,j,k;
while(scanf("%d",&t)!=EOF)
{
while(t--)
{
init();
if(fuck())
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: