还是差分约束,本题的约束条件没有等号,所以列不等式的时候可以把边放大1或缩小1。为了加入一个虚拟点以连通所有点,我把所有点往右移了一个位置,点下标要细心考虑不要设错了
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
static int n, m, d[102];
struct Edge
{
int u, v, w;
};
static int bellman_ford(struct Edge *array)
{
int i, j, u, v, w, flag;
for (i = 0; i <= n + 1; i++)
d[i] = INT_MAX;
d[0] = 0;
for (i = 0; i < n + 1; i++)
{
flag = 0;
for (j = 0; j <= m + n; j++)
{
u = array[j].u;
v = array[j].v;
w = array[j].w;
if (d[u] != INT_MAX && d[u] + w < d[v])
{
d[v] = d[u] + w;
flag = 1;
}
}
if (!flag)
break;
}
for (j = 0; j <= m + n; j++)
{
u = array[j].u;
v = array[j].v;
w = array[j].w;
if (d[u] != INT_MAX && d[u] + w < d[v])
return 0;
}
return 1;
}
int main()
{
int si, ni, ki;
char oi[3];
struct Edge *array = malloc(201 * sizeof(struct Edge));
while (scanf("%d", &n), n)
{
scanf("%d", &m);
int i;
for (i = 0; i < m; i++)
{
scanf("%d %d %s %d", &si, &ni, oi, &ki);
if (oi[0] == 'g')
{
array[i].u = si + ni + 1;
array[i].v = si;
array[i].w = -ki - 1;
}
else
{
array[i].u = si;
array[i].v = si + ni + 1;
array[i].w = ki - 1;
}
}
for (i = m; i <= m + n; i++)
{
array[i].u = 0;
array[i].v = i - m + 1;
array[i].w = 0;
}
puts(bellman_ford(array) ? "lamentable kingdom" : "successful conspiracy");
}
free(array);
return 0;
}