POJ 2983 Is the Information Reliable?

POJ_2983

有了前面做的题目的基础后,这个题目也还算比较好想到的。我们设S[i]为点i到直线上某参照点的距离(可以把0看做这个参照点),为了写起来方面,干脆把题目A north than B全部想像成B south than A,那么如果是输入P的时候,就应该有两个约束方程S[B]-S[A]>=XS[A]-S[B]>=-X,而输入V的时候,就只对应着一个约束方程S[B]-S[A]>=1

之后如果用最短路去做的话,实际上就是判断这个图是否存在负圈。为了使图连通起来,我们抽象出一个源点0,则对任意点i都有S[i]-S[0]>=0,这样便将图连通了起来,最后只要以0为起点,判断是否有负圈即可。

#include<stdio.h>
#include
<string.h>
int first[1010],next[210000],v[210000],w[210000];
int d[1010],q[1010],inq[1010],inedq[1010];
char b[5];
int main()
{
int i,j,k,A,B,X,N,M,u,e,ok,n,front,rear;
while(scanf("%d%d",&N,&M)==2)
{
e
=0;
memset(first,
-1,sizeof(first));
for(i=0;i<M;i++)
{
scanf(
"%s",b);
if(b[0]=='V')
{
scanf(
"%d%d",&A,&B);
v[e]
=A;
w[e]
=-1;
next[e]
=first[B];
first[B]
=e;
e
++;
}
else if(b[0]=='P')
{
scanf(
"%d%d%d",&A,&B,&X);
v[e]
=A;
w[e]
=-X;
next[e]
=first[B];
first[B]
=e;
e
++;
v[e]
=B;
w[e]
=X;
next[e]
=first[A];
first[A]
=e;
e
++;
}
}
for(i=1;i<=N;i++)
{
v[e]
=i;
w[e]
=0;
next[e]
=first[0];
first[
0]=e;
e
++;
}
for(i=0;i<=N;i++)
{
d[i]
=1000000000;
inq[i]
=inedq[i]=0;
}
d[
0]=0;
front
=rear=0;
q[rear
++]=0;
ok
=1;
n
=N+1;
while(front!=rear)
{
u
=q[front++];
inq[u]
=0;
if(front>n)
front
=0;
for(e=first[u];e!=-1;e=next[e])
if(d[u]+w[e]<d[v[e]])
{
d[v[e]]
=d[u]+w[e];
if(!inq[v[e]])
{
q[rear
++]=v[e];
if(rear>n)
rear
=0;
inq[v[e]]
=1;
if(++inedq[v[e]]>N)
{
ok
=0;
front
=rear;
break;
}
}
}
}
if(ok)
printf(
"Reliable\n");
else
printf(
"Unreliable\n");
}
return 0;
}

  

原文地址:https://www.cnblogs.com/staginner/p/2139780.html