题意:一个长度为n的数组,有m条限制。限制有两种P A B X:D[B]-D[A]==X,V A B:D[B]-D[A]>=1。请问是否存在可行的数组。是则输出Reliable,反之输出Unreliable。
思路:对于D[B]-D[A]==X,可以拆分成D[B]-D[A]>=X和D[B]-D[A]<=X两条不等式。此外因为建图后没有一个明确的起点,所以需要建立一个源点向每一个点建立一条长度为0的边。根据不等式建图,判环求解即可。
C++代码:
#include<map>
#include<set>
#include<stack>
#include<cmath>
#include<queue>
#include<vector>
#include<string>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 1010;
const int maxm = 200010;
const int inf = 0x3f3f3f3f;
int n,m,tol,head[maxn];
struct edge
{
int to,cost,next;
}es[maxm];
void init()
{
tol = 0;
memset ( head , -1 , sizeof(head) );
}
void addedge( int u , int v , int w )
{
es[tol].to = v;
es[tol].cost = w;
es[tol].next = head[u];
head[u] = tol++;
}
int dis[maxn];
int cnt[maxn];
int vis[maxn];
bool spfa()
{
memset ( vis , 0 , sizeof(vis) );
memset ( cnt , 0 , sizeof(cnt) );
memset ( dis , inf , sizeof(dis) );
queue<int>Q;
Q.push(0);
vis[0] = 1;
dis[0] = 0;
cnt[0] = 1;
while ( !Q.empty() )
{
int u = Q.front();
Q.pop();
vis[u] = 0;
for ( int i=head[u] ; i!=-1 ; i=es[i].next )
{
int v = es[i].to,w = es[i].cost;
if ( dis[v]>dis[u]+w )
{
dis[v] = dis[u]+w;
if ( !vis[v] )
{
vis[v] = 1;
Q.push(v);
cnt[v] ++;
if ( cnt[v]>n )
return false;
}
}
}
}
return true;
}
int main()
{
while ( scanf ( "%d%d" , &n , &m )==2 )
{
init();
for ( int i=1 ; i<=m ; i++ )
{
char op[5]; int a,b,x;
scanf ( "%s" , op );
if ( op[0]=='P' )
{
scanf ( "%d%d%d" , &a , &b , &x );
addedge( a , b , x );
addedge( b , a , -x );
}
else
{
scanf ( "%d%d" , &a , &b );
addedge( b , a , -1 );
}
}
for ( int i=1 ; i<=n ; i++ )
addedge ( 0 , i , 0 );
if ( spfa() )
printf ( "Reliable\n" );
else
printf ( "Unreliable\n" );
}
return 0;
}