贴代码也行吧。
#include <bits/stdc++.h>
using namespace std;
#define INF 2147483647
int n, m, cnt = 0;
struct edge
{
int w, to, nxt;
}e[5001];
int h[5001], dis[5001];
bool vis[5001];
int sum[5001];
queue<int> q;
inline void add(int u, int v, int w) //链式前向星
{
e[++cnt].to = v;
e[cnt].w = w;
e[cnt].nxt = h[u];
h[u] = cnt;
}
inline bool SPFA(int s)
{
for(int i = 0; i <= n; i++)
dis[i] = INF;
dis[s] = 0; vis[s] = 1; sum[s] = 1;
q.push(1);
while(!q.empty())
{
int u = q.front(); q.pop();
vis[u] = 0;
for(int i = h[u]; i; i = e[i].nxt)
{
int v = e[i].to;
if(dis[v] > dis[u] + e[i].w)
{
dis[v] = dis[u] + e[i].w;
if(!vis[v])
{
vis[v] = 1;
q.push(v);
sum[v]++;
if(sum[v] == n + 1) return 0;
}
}
}
}
return 1;
}
inline int read()
{
int x = 0, f = 1;
char ch = getchar();
while(ch < '0' || ch > '9')
{
if(ch == '-') f = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9')
{
x = (x << 1) + (x << 3) + (ch ^ 48);
ch = getchar();
}
return x * f;
}
int main()
{
n = read(), m = read();
for(int i = 1; i <= m; i++) //差分约束
{
int opt = read();
int a = read(), b = read();
if(opt == 1) //a <= b + 0, b <= a + 0
add(a, b, 0), add(b, a, 0);
if(opt == 2) //a <= b - 1
add(a, b, -1);
if(opt == 3) //b <= a + 0
add(b, a, 0);
if(opt == 4) //b <= a - 1
add(b, a, -1);
if(opt == 5) //a <= b + 0
add(a, b, 0);
}
if(!SPFA(n + 1)) printf("-1");
//?????
return 0;
}