2019CCPC哈尔滨E. Exchanging Gifts

给定$n$个格子

  • 对于前M1个约束,区间$[L,R]$内取的数量必须严格不少于K

  • 对于后M2个约束,区间$[L,R]$外取的数量必须严格不少于K

  • 满足所有M1+M2个约束的前提下使得取的个数最少,输出最少取的个数

    转化一下

然后答案满足单调性。
注意!!!

跑一遍差分约束即可,

1
2
3
cnt[to] = cnt[x] + 1;
if(dis[to]<0)
return false;

注意这两个剪枝点即可。

代码
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define pii pair<int, int>
#define mk make_pair
const int N = 1e6 + 10;
const int mod = 1e9 + 7;
int read()
{
int x = 0, f = 1;
char c = getchar();
while (c < '0' || c > '9')
{
if (c == '-')
f = -1;
c = getchar();
}
while (c >= '0' && c <= '9')
x = (x << 1) + (x << 3) + c - '0', c = getchar();
return x * f;
}
struct Node
{
int l, r, w;
} q[N];
int n, m1, m2;
int vis[N], cnt[N], dis[N];
vector<pii> g[N];
bool check(int mid)
{
for (int i = 0; i <= n; i++)
g[i].clear(), vis[i] = 0, dis[i] = 1e9, cnt[i] = 0;
for (int i = 1; i <= n; i++)
{
g[i - 1].push_back(mk(i, 1));
g[i].push_back(mk(i - 1, 0));
}
for (int i = 1; i <= m1; i++)
{
g[q[i].r].push_back(mk(q[i].l, -q[i].w));
}

for (int i = m1 + 1; i <= m2 + m1; i++)
{

if (mid - q[i].w < 0)
return false;
g[q[i].l].push_back(mk(q[i].r, mid - q[i].w));
}
g[0].push_back({n, mid});
g[n].push_back({0, -mid});
queue<int> q;

q.push(0);
dis[0] = 0;
vis[0] = 1;

while (!q.empty())
{
int x = q.front();
q.pop();
vis[x] = 0;
for (pii now : g[x])
{
int to = now.first;

if (dis[to] > dis[x] + now.second)
{
dis[to] = dis[x] + now.second;

if (!vis[to])
{
cnt[to] = cnt[x] + 1;
if (cnt[to] > n)
return false;
q.push(to);
vis[to] = 1;
}
}
}
}

return true;
}
int main()
{
int T = read();
while (T--)
{
n = read(), m1 = read(), m2 = read();
for (int i = 1; i <= m1 + m2; i++)
q[i].l = read() - 1, q[i].r = read(), q[i].w = read();
int l = 0, r = n, ans = n;
while (l <= r)
{
int mid = (l + r) >> 1;
if (check(mid))
{
ans = mid;
r = mid - 1;
}
else
{
l = mid + 1;
}
}

printf("%d\n", ans);
}
}