The galaxy war between the Empire Draco and the Commonwealth of Zibu broke out 3 years ago. Draco established a line of defense called Grot. Grot is a straight line with N defense stations. Because of the cooperation of the stations, Zibu’s Marine Glory cannot march any further but stay outside the line.
A mystery Information Group X benefits form selling information to both sides of the war. Today you the administrator of Zibu’s Intelligence Department got a piece of information about Grot’s defense stations’ arrangement from Information Group X. Your task is to determine whether the information is reliable.
The information consists of M tips. Each tip is either precise or vague.
Precise tip is in the form of P A B X
, means defense station A is X light-years north of defense station B.
Vague tip is in the form of V A B
, means defense station A is in the north of defense station B, at least 1 light-year, but the precise distance is unknown.
Input
There are several test cases in the input. Each test case starts with two integers N(0 < N ≤ 1000) and M (1 ≤ M ≤ 100000).The next M line each describe a tip, either in precise form or vague form.
Output
Output one line for each test case in the input. Output “Reliable” if It is possible to arrange N defense stations satisfying all the M tips, otherwise output “Unreliable”.
Sample Input
3 4 P 1 2 1 P 2 3 1 V 1 3 P 1 3 1 5 5 V 1 2 V 2 3 V 3 4 V 4 5 V 3 5
Sample Output
Unreliable Reliable
P时:dis[a]-dis[b]==X 可以转化为dis[a]-dis[b]>=X和dis[a]-dis[b]<=X,
V时:dis[a]-dis[b]>=1
把大于等于反过来变成小于等于,跑最短路即可,注意图可以不连通,所以先建一个汇点0,到个点距离均为0,还有判断不成立的条件是看是否有负环,因为如果有负环,距离可以一直减小,无最短路,
最短路用spfa算法加链式前向星,可以直接用入队的节点数目判断是否成环
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define inf 0x3f3f3f3f
#include<queue>
#define maxn 5005
#define maxm 500005
using namespace std;
struct egde
{
int next,v,w;
}edges[2*maxm];
int head[maxn];
int vis[maxn];
int num[maxn];
int dis[maxn];
int cnt;
int n,m;
void init()
{
memset(head,-1,sizeof(head));
cnt=0;
}
void addedge(int u,int v,int w)
{
edges[cnt].v=v;
edges[cnt].w=w;
edges[cnt].next=head[u];
head[u]=cnt++;
}
int spfa()
{memset(vis,0,sizeof(vis));
memset(num,0,sizeof(num));
queue<int>q;
for(int i=0;i<=maxn;i++)
dis[i]=inf;
vis[0]=1;
dis[0]=0;
num[0]=1;
q.push(0);
while(!q.empty())
{
int u=q.front();
q.pop();
vis[u]=0;
num[u]++;
if(num[u]>n)
return 0;
for(int i=head[u];i!=-1;i=edges[i].next)
{
int v=edges[i].v;
int w=edges[i].w;
if(dis[v]>dis[u]+w)
{
dis[v]=dis[u]+w;
if(!vis[v])
{
vis[v]=1;
q.push(v);
}
}
}
}
return 1;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
char str[10];
int u,v,x;
init();
while(m--)
{
scanf("%s",str);
if(str[0]=='P')
{scanf("%d%d%d",&u,&v,&x);
addedge(v,u,x);
addedge(u,v,-x);
}
else if(str[0]=='V')
{scanf("%d%d",&u,&v);
addedge(u,v,-1);
}
}
for(int i=1;i<=n;i++)
addedge(0,i,0);
if(spfa())
printf("Reliable\n");
else
printf("Unreliable\n");
}
return 0;
}