0%

BZOJ 3436 解题报告

题意描述

给定\(n\)个变量和\(m\)个式子,形如: \[a \geq b + c\] \[a \leq b + c\] \[a = b\] 这些变量必须为非负整数,如果能找到一组可行解,输出"Yes",否则输出"No"。

时间限制(总):10s 空间限制:128MB

题目链接

BZOJ 3436

题解

差分约束系统的典型题,转化给定的约束条件: \[a \geq b + c \Leftrightarrow a + (-c) \geq b\] \[a \leq b + c \Leftrightarrow b + c \geq a\] \[a = b \Leftrightarrow a + 0 \geq b 且 b + 0 \geq a\] 对于以上三种约束条件,建图方式为:

  1. 从点\(a\)向点\(b\)连一条权值为\(-c\)的边。
  2. 从点\(b\)向点\(a\)连一条权值为\(c\)的边。
  3. 从点\(a\)向点\(b\)连一条权值为\(0\)的边,从点\(b\)向点\(a\)连一条权值为\(0\)的边。

然后跑最短路,因为题目只是要求检查是否有可行解,所以使用dfs-SPFA判负环。注意这里要遍历每一个联通块。(或者新建一个虚点向所有节点连边,然后以虚点为起点跑一次最短路)

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <cstdio>
#include <algorithm>
#include <cstring>

using namespace std;

const int MAXN = 10010;
const int MAXM = 20010;

template<typename T>
T read() {
T result = 0;int f = 1;char c = getchar();
while(c > '9' || c < '0') {if(c == '-') f *= -1;c = getchar();}
while(c <= '9' && c >= '0') {result = result * 10 + c - '0';c = getchar();}
return result * f;
}

struct Graph {
struct Edge {
int next,to,weight;
};
Edge edges[MAXM];
int tot,heads[MAXN];

Graph() : tot(0) {
memset(heads,-1,sizeof(heads));
}

void addEdge(int u,int v,int w) {
edges[tot].next = heads[u];
edges[tot].to = v;
edges[tot].weight = w;
heads[u] = tot++;
}
} graph;

int dis[MAXN];
bool visit[MAXN],found;


void spfa(int now) {
visit[now] = true;
for(int i = graph.heads[now];i != -1;i = graph.edges[i].next) {
Graph::Edge &tmpEdge = graph.edges[i];
if(dis[tmpEdge.to] <= dis[now] + tmpEdge.weight) continue;
if(visit[tmpEdge.to]) {
found = true;
return;
}
dis[tmpEdge.to] = dis[now] + tmpEdge.weight;
spfa(tmpEdge.to);
if(found) return;
}
visit[now] = false;
}

int main() {
int n = read<int>(),m = read<int>();
for(int i = 0;i < m;i++) {
int type = read<int>(),a = read<int>(),b = read<int>();
if(type == 1) {
int c = read<int>();
graph.addEdge(a,b,-c);
}else if(type == 2) {
int c = read<int>();
graph.addEdge(b,a,c);
}else {
graph.addEdge(a,b,0);
graph.addEdge(b,a,0);
}
}
for(int i = 1;i <= n;i++) {
spfa(i);
if(found) break;
}
if(found) {
printf("No\n");
}else {
printf("Yes\n");
}
return 0;
}