poj2983

bellman_ford判断负环优化版

#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
const int INF = 1<<26;
struct node{
int s;//开始点
int w;//权值
int e;//结束点
}edge[200005];
int dis[1005],n,m,mi;
bool bellman_ford(){
int i,j;
bool sign;//用于Bellman-Ford算法优化
memset(dis,0,sizeof(dis));
for(i=1;i<=n;i++)
{
sign = false;
for(j=0;j<mi;j++)
{
if(dis[edge[j].e]>dis[edge[j].s]-edge[j].w)
{
dis[edge[j].e]=dis[edge[j].s]-edge[j].w;
sign = true;
}
}
if(!sign)//若dis没有任何改变,则以后也不会改变,可以直接退出循环
break;
}
return sign;
}
int main()
{
int i,j;
int x,y,v;
char s[3];
while(scanf("%d %d",&n,&m)!=EOF)
{
for(i=0,mi=0;i<m;i++)
{
scanf( "%s",s);
if( s[0]=='P' )
{
scanf( "%d%d%d",&x,&y,&v);
edge[mi].s=x;
edge[mi].w=v;
edge[mi++].e=y;
edge[mi].s=y;
edge[mi].w=-v;
edge[mi++].e=x;
}
else if(s[0] == 'V')
{
scanf( "%d%d",&x,&y);
edge[mi].s=x;
edge[mi].w=1;
edge[mi++].e=y;
}
}
if(bellman_ford())
printf("Unreliable\n");//存在负权环
else
printf("Reliable\n"); //不存在负权环
}
return 0;
}

 

你可能感兴趣的:(include)