poj2983

题意:给出一些不等式,求是否存在可行解。

分析:差分约束系统,对于bellman和spfa来说,解差分的不同在于,对于不连通图bellman能直接处理,而spfa不能,需要加入超级源(一个到所有点都有一条长度为0的边的点),并把超级源作为起点,才能保证在扩展过程中到达每个点。否则差分约束系统的部分内容就不会被检测到。当然也不是所有题遇到这种不连通的情况都可以使用超级源。因为这种超级源相当于把不同的连通分支在数轴上的起点都平移到了原点。如题目有特殊要求,则可以对不同的连通分支分别做单独处理。

View Code
#include <iostream>
#include
<cstdio>
#include
<cstdlib>
#include
<cstring>
usingnamespace std;

#define maxn 1005
#define maxm 100005
#define inf 0x3f3f3f3f

struct Edge
{
int v, w, next;
} edge[maxm
*3];

int n, m;
int head[maxn];
int vis[maxn], cost[maxn];
bool inq[maxn];
int q[maxn];
bool ok;
int ecount;

void addedge(int a, int b, int w)
{
edge[ecount].next
= head[a];
head[a]
= ecount;
edge[ecount].v
= b;
edge[ecount].w
= w;
ecount
++;
}

void input()
{
getchar();
for (int i =0; i < m; i++)
{
char ch;
int a, b, c;
scanf(
"%c", &ch);
if (ch =='V')
{
scanf(
"%d%d", &a, &b);
if (a == b)
ok
=false;
addedge(b, a,
1);
}
else
{
scanf(
"%d%d%d", &a, &b, &c);
if (a == b && c !=0)
ok
=false;
addedge(b, a, c);
addedge(a, b,
-c);
}
getchar();
}
for (int i =1; i <= n; i++)
addedge(
0, i, 0);
}

bool relax(int a, int b, int w)
{
if (cost[b] < cost[a] + w)
{
cost[b]
= cost[a] + w;
returntrue;
}
returnfalse;
}

bool spfa()
{
memset(vis,
0, sizeof(vis));
memset(inq,
0, sizeof(inq));
for (int i =0; i <= n; i++)
cost[i]
=-inf;
int front =0, rear =1;
cost[
0] =0;
q[
0] =0;
inq[
0] =true;
while (front != rear)
{
int u = q[front++];
if (front == maxn)
front
=0;
inq[u]
=false;
for (int i = head[u]; i !=-1; i = edge[i].next)
{
int v = edge[i].v;
if (relax(u, v, edge[i].w) &&!inq[v])
{
q[rear
++] = v;
inq[v]
=true;
vis[v]
++;
if (vis[v] > n)
returnfalse;
if (rear == maxn)
rear
=0;
}
}
}
returntrue;
}

int main()
{
//freopen("t.txt", "r", stdin);
while (scanf("%d%d", &n, &m) != EOF)
{
memset(head,
-1, sizeof(head));
ecount
=0;
ok
=true;
input();
if (spfa() && ok)
printf(
"Reliable\n");
else
printf(
"Unreliable\n");
}
return0;
}
原文地址:https://www.cnblogs.com/rainydays/p/2098895.html