我在机房并且忘了 SPOJ 账号密码,但是这份代码可以通过 P4115 Qtree4。等我有时间交到 SPOJ 上看看。

点分树(动态点分治)板子。

既然是动态点分治,我们就先思考静态版本(这个是 P2971 )。给定一些点怎么做?这个有很多种方法(我在 P2971 用的是虚树)。我们考虑点分治做法。

对于每个分支中心和它的各个子节点的子树,我们统计子树中的点到它的距离的最大值 $v$。两棵子树的 $v$ 加起来取最大值,和所有的 $v$ 的最大值再取最大值(当且仅当分治中心本身可用),就是所有跨越路径的最大值。

那么对于一个节点 $u$,设它的上一层的分治中心(即,$u$ 作为分治中心的那一次递归,它的上一层节点。也就是点分树上它的父亲)为 $f_u$。对于每个 $u$ 维护一个数据结构,维护所有当前可用节点到 $f_u$ 的距离。要求支持插入,删除和查询 $\max$,我们用可删堆(实际上只需要支持禁用,启用和查询启用的最大值,所以这样一个线段树也可以)。设为 $H_u$。

同时,在 $u$ 中另外设一个可删除 $Q_u$。它存储它的所有儿子节点的 $H$ 的最大值。同样需要支持求 $\max$,也需要支持求次大值。这个删除最大值即可。一样,只需要支持单点修改,所以线段树也可以。

一个实现细节是,如果 $u$ 本身可用,则需要在 $Q$ 中插入一个 $0$,否则不用。原因上面已经讲过。

最后设一个全局的可删堆 $K$,保存所有 $Q$ 的最大值和次大值之和的最大值。同样只需要支持单点修改,所以线段树也可以。答案就是 $K$ 的最大值。注意有些情况下 $K$ 的最大值可能为负,所以请对 $0$ 取 $\max$。

最后我们用三组(个)堆 $H,Q,K$ 解决了这个问题。时间复杂度 $O((n+q)\log^2 n)$。膜拜 hqk。

需要一定程度的常数优化。

rec&code

是 P4115 的。洛谷交不上。

rec。

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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#include <queue>
#include <bitset>
#include <cstdio>
#include <vector>
#include <utility>
#include <algorithm>

using namespace std;

const auto U = [](auto x) { return [x](auto ...y) { return x(x, y...); }; };
class delheap { priority_queue<int> has, del; bool modified = false; int secmax = 0; void maintain() { while(!del.empty() && has.top() == del.top()) { has.pop(); del.pop(); } } public: void insert(int x) { modified = true; has.push(x); } void erase(int x) { modified = true; del.push(x); } int qmax() { maintain(); return has.top(); } int qmps() { int t = qmax(); if(!modified) return t + secmax; modified = false; erase(t); secmax = qmax(); insert(t); return t + secmax; } };
delheap chxs[100005], gmr[100005], gans;
vector<pair<unsigned, int>> web[100005];
unsigned decfa[100005];
bitset<100005> stat;
unsigned dep[100005];
unsigned fa[20][100005];
int fv[20][100005]; // \uparrow

#ifndef __linux__
#define getchar_unlocked _getchar_nolock
#endif

char ibf[50000005];
unsigned li = 0;

int qread()
{
int ans = 0, fw = 1;
char ch;
while((ch = ibf[li++]) < '0' || ch > '9') if(ch == '-') fw = -1;
do
{
ans = ans * 10 + (ch - '0');
} while((ch = ibf[li++]) >= '0' && ch <= '9');
return ans * fw;
}
unsigned uqread()
{
unsigned ans = 0;
char ch;
while((ch = ibf[li++]) < '0' || ch > '9');
do
{
ans = ans * 10 + (ch - '0');
} while((ch = ibf[li++]) >= '0' && ch <= '9');
return ans;
}

int main()
{
fread(ibf, 1, sizeof ibf, stdin);
unsigned n = uqread();
for(unsigned i=1;i<n;i++)
{
unsigned u, v;
int w;
u = uqread(); v = uqread(); w = qread();
web[u].push_back({v, w});
web[v].push_back({u, w});
}
auto cent = [](unsigned rt) -> int
{
unsigned tot = 0;
U([&](auto &&self, unsigned u, unsigned ff) -> void { tot++; for(const auto &[v, w] : web[u]) if(v != ff && !stat[v]) self(self, v, u); })(rt, 0);
return -U([&](auto &&self, unsigned u, unsigned ff) -> int { unsigned sum = 1, maxn = 0; for(const auto &[v, w] : web[u]) if(v != ff && !stat[v]) { int res = self(self, v, u); if(res < 0) return res; sum += (unsigned)res; maxn = max(maxn, (unsigned)res); } maxn = max(maxn, tot - sum); /*printf("[cent lambda 2] u = %d, sum = %d, maxn = %d\n", u, sum, maxn);*/ if(maxn <= tot / 2) return -u; else return sum; })(rt, 0);
};
U([&](auto &&self, unsigned u) -> void
{
// printf("fa[%d][%u] = %u, fv[%d][%u] = %d\n", 0, u, fa[0][u], 0, u, fv[0][u]);
for(unsigned i=1;(1u<<i)<=dep[u];i++)
{
fa[i][u] = fa[i-1][fa[i-1][u]];
fv[i][u] = fv[i-1][u] + fv[i-1][fa[i-1][u]];
// printf("fa[%d][%u] = %u, fv[%d][%u] = %d\n", i, u, fa[i][u], i, u, fv[i][u]);
}
for(const auto &[v, w] : web[u])
{
if(v != fa[0][u])
{
dep[v] = dep[u] + 1;
fa[0][v] = u;
fv[0][v] = w;
self(self, v);
}
}
})(1);
auto qsum = [](unsigned u, unsigned v) -> int
{
int sum = 0;
for(int i=16;i>=0;i--)
{
if(dep[u] >= dep[v] + (1u << i))
{
sum += fv[i][u];
u = fa[i][u];
}
else if(dep[v] >= dep[u] + (1u << i))
{
sum += fv[i][v];
v = fa[i][v];
}
if(u == v) break;
}
if(u == v) return sum;
for(int i=16;i>=0;i--)
{
if(fa[i][u] != fa[i][v])
{
sum += fv[i][u] + fv[i][v];
u = fa[i][u];
v = fa[i][v];
}
}
return sum + fv[0][u] + fv[0][v];
};
U([&](auto &&self, unsigned u, unsigned ffa) -> unsigned
{
u = cent(u);
// printf("[dfs] u = %d, ffa = %d\n", u, ffa);
gmr[u].insert(-0x3f3f3f3f);
if(ffa) U([&](auto &&sel, unsigned x, unsigned ff) -> void { gmr[u].insert(qsum(x, ffa)); for(const auto &[y, w] : web[x]) if(y != ff && !stat[y]) sel(sel, y, x); })(u, 0);
stat[u] = true;
chxs[u].insert(-0x3f3f3f3f);
chxs[u].insert(0);
for(const auto &[v, w] : web[u])
{
if(!stat[v])
{
unsigned res = self(self, v, u);
// decch[u].push_back(res);
decfa[res] = u;
chxs[u].insert(gmr[res].qmax());
}
}
// printf("chxs[%u]: ", u); chxs[u].print(); printf("\n");
// printf("gmr[%u]: ", u); gmr[u].print(); printf("\n");
gans.insert(chxs[u].qmps());
return u;
})(1, 0);
// printf("qsum(4, 2) = %d\n", qsum(4, 2));
unsigned q = uqread();
unsigned cnt = n;
while(q--)
{
char op;
while((op = ibf[li++]) != 'A' && op != 'C');
// op = getchar_unlocked();
if(op == 'A')
{
if(!cnt) puts("They have disappeared.");
else printf("%d\n", max(0, gans.qmax()));
}
else
{
unsigned u;
u = uqread();
if(stat[u])
{
cnt--;
unsigned x = u;
while(x)
{
if(decfa[x])
{
int yy = chxs[decfa[x]].qmps();
int xx = gmr[x].qmax();
gmr[x].erase(qsum(u, decfa[x]));
if(xx != gmr[x].qmax())
{
chxs[decfa[x]].erase(xx);
chxs[decfa[x]].insert(gmr[x].qmax());
}
if(yy != chxs[decfa[x]].qmps())
{
gans.erase(yy);
gans.insert(chxs[decfa[x]].qmps());
}
}
x = decfa[x];
}
stat[u] = false;
int xx = chxs[u].qmps();
chxs[u].erase(0);
if(chxs[u].qmps() != xx)
{
gans.erase(xx);
gans.insert(chxs[u].qmps());
}
}
else
{
cnt++;
unsigned x = u;
while(x)
{
if(decfa[x])
{
int yy = chxs[decfa[x]].qmps();
int xx = gmr[x].qmax();
gmr[x].insert(qsum(u, decfa[x]));
if(xx != gmr[x].qmax())
{
chxs[decfa[x]].erase(xx);
chxs[decfa[x]].insert(gmr[x].qmax());
}
if(yy != chxs[decfa[x]].qmps())
{
gans.erase(yy);
gans.insert(chxs[decfa[x]].qmps());
}
}
x = decfa[x];
}
stat[u] = true;
int xx = chxs[u].qmps();
chxs[u].insert(0);
if(chxs[u].qmps() != xx)
{
gans.erase(xx);
gans.insert(chxs[u].qmps());
}
}
}
}
return 0;
}

奇怪的全局点对路径问题,考虑点分治。

那么只需要考虑跨越点对。怎么做?

首先考虑经典做法,二叉合并,逐子树考虑(二叉合并写多了也要会写容斥!)。

对于每一个新的子树中的点,假设它到分治中心的距离为 $l$,所有边的边权的 $\max$ 为 $v$,那么它可以和前面的子树中所有距离 $\in [R-l,L-l]$ 的点产生贡献。

这个 $\max$ 不好做。主要是产生的贡献不好统计。考虑分成两部分:小于等于和大于。

这样转化为二维平面就可以是一个单点加法,子矩形求和。树套树。总时间复杂度(算上点分治)$O(n\log^3 n)$,能过,但是我们考虑更优做法。

还是这个 $\max$ 麻烦。我们考虑另一种做法:按照 $v$ 从小到大排序,这样新遇到的一个点和前面的点的 $\max$ 一定是这个点的 $v$。

这样一个树状数组处理个数就可以了。单点加法区间求和,非常好。

这个做法有一个问题:一个子树可以和它自己产生贡献。解决方法是显然的,我们用容斥即可,把所有子树内部产生的贡献单独计算,并扣除即可。

时间复杂度 $O(n\log^2n)$,只有一个数据结构:树状数组。

rec&code

rec。

代码极其丑陋,看之前请先确保自己不会呕吐。

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
#include <cstdio>
#include <vector>
#include <utility>
#include <algorithm>

using namespace std;

const auto U = [](auto x) { return [x](auto ...y) { return x(x, y...); }; };
vector<pair<int, int>> web[100005];
bool forbid[100005];
class fenwick { long long st[100005]; public: void vadd(int pos, int val, int n) { pos++; do { st[pos] += val; } while((pos += pos & -pos) <= n); } long long qsum(int pos) { pos++; long long sum = 0; do { sum += st[pos]; } while(pos -= pos & -pos); return sum; } } fw;

int main()
{
int n, l, r;
scanf("%d%d%d", &n, &l, &r);
for(int i=2;i<=n;i++)
{
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
web[u].push_back({v, w});
web[v].push_back({u, w});
}
auto cent = [](int rt) -> int
{
int tot = 0;
U([&](auto &&self, int u, int fa) -> void { tot++; for(const auto &[v, w] : web[u]) if(v != fa && !forbid[v]) self(self, v, u); })(rt, 0);
return -U([&](auto &&self, int u, int fa) -> int { int sum = 1, maxn = 0; for(const auto &[v, w] : web[u]) if(v != fa && !forbid[v]) { int res = self(self, v, u); if(res < 0) return res; sum += res; maxn = max(maxn, res); } maxn = max(maxn, tot - sum); if(maxn <= tot / 2) return -u; else return sum; })(rt, 0);
};
auto calc = [l, r](int rt, int vlen, int vmax) -> long long
{
// printf("[calc] rt = %d, vlen = %d, vmax = %d\n", rt, vlen, vmax);
vector<pair<int, int>> vpii;
U([&](auto &&self, int u, int fa, int len, int maxn) -> void { vpii.push_back({maxn, len}); for(const auto &[v, w] : web[u]) if(v != fa && !forbid[v]) self(self, v, u, len + 1, max(maxn, w)); })(rt, 0, vlen, vmax);
sort(vpii.begin(), vpii.end());
long long sum = 0;
for(const auto &[maxn, len] : vpii)
{
if(len <= r) sum += maxn * fw.qsum(r - len);
if(len <= l - 1) sum -= maxn * fw.qsum(l - len - 1);
fw.vadd(len, 1, 100000);
}
for(const auto &[maxn, len] : vpii)
{
fw.vadd(len, -1, 100000);
}
return sum;
};
printf("%lld\n", U([&](auto &&self, int u) -> long long
{
u = cent(u);
long long sum = calc(u, 0, 0);
forbid[u] = true;
for(const auto &[v, w] : web[u])
{
if(!forbid[v]) sum -= calc(v, 1, w);
}
// printf("u = %d, gets %lld\n", u, sum);
for(const auto &[v, w] : web[u])
{
if(!forbid[v]) sum += self(self, v);
}
// forbid[u] = false;
return sum;
})(1) * 2);
return 0;
}

$root$ 这个取名真的太有提示性了。

这篇题解本应当有图片,但是我不想用洛谷图床,所以请大家自行脑补。另外,所有图片的占位符也被删除。


首先很显然的一个事情就是,如果选取的根节点合法,那么每个子树两两同构,且也都要合法(其实这是充要的)。

我们先考虑同构。根据 CF1252F 的结论,显然选取的节点要么是重心,要么是叶子(CF1252F 中规定了不能是叶子,但是其实叶子也是可以的)。如果没做过也没事,显然同构的必要条件就是大小相同,如果有 $\ge 2$ 个邻居则必然每个邻居的连通块大小都要 $\le \dfrac{n}{2}$,这个点就是重心。否则,只有一个邻居,就是叶子。

重心是好解决的,因为最多有两个,只需要暴力判断即可。叶子?

我们考虑以某个叶子 $g$ 为根,从上往下找到第一个子节点个数 $\ge 2$ 的点,设为 $u$。那么这个叶子合法,当且仅当去掉 $u$ 的严格祖先链(不包括 $u$)中所有节点后,以 $u$ 为根时合法。

我们考虑继续使用必要条件——重心。$u$ 必须是修改后的树的重心。那么,我们考虑修改后的树,在这棵树上,$u$ 的每个邻居的大小都要 $\ge \dfrac{m}{2}$,$m$ 是修改后的树的大小,自然也就 $<\dfrac{n}{2}$。

也就是说,$u$ 要么是重心,要么唯一一个大小 $>\dfrac{n}{2}$ 的邻居子树就是它到叶子节点 $g$ 的方向的邻居,也就是一条链。

等下,后者可能吗?不行,因为它到 $g$ 的方向的子树大小不然不多于重心(随便选一个)到 $g$ 的方向的大小,必然 $\ge \dfrac{n}{2}$。矛盾了!

所以只可能 $u$ 本身就是重心。

阶段性总结一下,合法的根节点有两种可能:

  • 这个节点是树的重心。
  • 这个节点是从树的重心开始,沿着某一条纯链(没有任何多余节点的链,除了开头)一直走,走到某一个叶子的节点。

我们还是需要着重处理后者。

后者什么时候合法?假设重心 $c$ 到这个节点的方向上第一个节点是 $u$,那么就相当于删除 $u$ 的子树之后整棵树以 $c$ 为根时合法。

这就非常好做了。注意到纯链也是合法的结构,所以相当于:

  • $c$ 的所有邻居均合法。
  • $c$ 的所有除 $u$ 之外的邻居均同构(根节点就是 $c$ 的邻居)。

直接做就行。时间复杂度 $O(n)$。

sub&code

sub。

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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
#include <cstdio>
#include <vector>
#include <random>
// #include <cassert>
#include <algorithm>

using namespace std;
#define assert(x) if(!(x)) printf("Line %d", __LINE__)

const auto U = [](auto x) { return [x](auto ...y) { return x(x, y...); }; };

vector<int> web[100005];
bool forbids[100005];

int main()
{
int n;
scanf("%d", &n);
// n = 6;
if(n == 1)
{
printf("1\n");
return 0;
}
mt19937_64 mt(random_device{}());
for(int i=2;i<=n;i++)
{
int u, v;
scanf("%d%d", &u, &v);
// v = i;
// u = uniform_int_distribution<int>(1, i-1)(mt);
// printf("%d %d\n", u, v);
web[u].push_back(v);
web[v].push_back(u);
}
auto cent = [](int rt) -> vector<int>
{
// printf("[cent] rt = %d\n", rt);
int tot = 0;
U([&](auto &&self, int u, int fa) -> void { tot++; for(int v : web[u]) if(v != fa && !forbids[v]) self(self, v, u); })(rt, 0);
vector<int> ans;
// printf("tot = %d\n", tot);
U([&](auto &&self, int u, int fa) -> int { int sum = 1, maxn = 0; for(int v : web[u]) if(v != fa && !forbids[v]) { int res = self(self, v, u); sum += res; maxn = max(maxn, res); } maxn = max(maxn, tot - sum); if(maxn <= tot / 2) ans.push_back(u); return sum; })(rt, 0);
// printf("sz = %d\n", (int)ans.size());
return ans;
};
unsigned long long hvx = ((unsigned long long)random_device{}() << 32) | random_device{}(), hvm;
do
{
hvm = ((unsigned long long)random_device{}() << 32) | random_device{}();
} while(hvm % 2 == 0);
auto rootedhash = U([&](auto &&self, int u, int fa) -> unsigned long long
{
unsigned long long val = 33550336;
for(int v : web[u])
{
if(v != fa && !forbids[v])
{
val += (hvx ^ ((hvx ^ self(self, v, u)) * hvm));
}
}
return val;
});
auto thash = [&](int u) -> vector<unsigned long long>
{
vector<unsigned long long> res;
for(int x : cent(u))
{
res.push_back(rootedhash(x, 0));
}
sort(res.begin(), res.end());
return res;
};
auto qtype = [](int rt) -> int
{
vector<int> ds;
bool flag = true;
U([&](auto &&self, int u, int fa, int dep) -> void { int cnt = 0; for(int v : web[u]) if(!forbids[v]) cnt++; if(ds.size() <= dep) ds.push_back(cnt); else if(ds[dep] != cnt) flag = false; for(int v : web[u]) if(v != fa && !forbids[v]) self(self, v, u, dep + 1); })(rt, 0, 0);
if(ds.size() == 1) return 1;
if(!flag) return -1;
for(int i=0;i<ds.size();i++)
{
if((i == 0 || i + 1 == ds.size()) && ds[i] != 1) return 0;
if(i > 0 && i + 1 < ds.size() && ds[i] != 2) return 0;
}
return 1;
};
// int maxn = -1;
for(int g : cent(1))
{
// printf("g = %d\n", g);
forbids[g] = true;
/*
1. 所有子树均合法且同构
2. 有一棵子树是是链,其余均同构
*/
unsigned long long X = 0;
vector<pair<int, unsigned long long>> Y;
bool flag = false;
for(int u : web[g])
{
int res = qtype(u);
if(res == -1)
{
flag = true;
break;
}
else if(res == 0)
{
if(!X) X = rootedhash(u, 0);
else if(X != rootedhash(u, 0))
{
flag = true;
break;
}
}
else Y.push_back({u, rootedhash(u, 0)});
}
if(flag)
{
forbids[g] = false;
continue;
}
if(!X)
{
// printf("?\n");
unsigned long long a = 0, b = 0;
int ca = 0, cb = 0, ka = 0, kb = 0;
for(const auto &x : Y)
{
if(!a)
{
ca = 1;
a = x.second;
ka = x.first;
}
else if(x.second == a) ca++;
else if(!b)
{
cb = 1;
b = x.second;
kb = x.first;
}
else if(x.second == b) cb++;
else
{
flag = true;
break;
}
}
if(flag)
{
// printf("!\n");
forbids[g] = false;
continue;
}
if(ca == 1)
{
// printf("ka = %d\n", ka);
int lst = g, nw = ka;
while(web[nw].size() == 2)
{
if(web[nw][0] == lst)
{
lst = nw;
nw = web[nw][1];
}
else
{
lst = nw;
nw = web[nw][0];
}
}
forbids[g] = false;
// assert(web[nw].size() == 1);
assert(qtype(nw) != -1);
if(qtype(nw) != -1) printf("%d\n", nw);
return 0;
}
else if(cb == 0)
{
printf("%d\n", g);
return 0;
}
else if(cb == 1)
{
// printf("kb = %d\n", kb);
int lst = g, nw = kb;
while(web[nw].size() == 2)
{
if(web[nw][0] == lst)
{
lst = nw;
nw = web[nw][1];
}
else
{
lst = nw;
nw = web[nw][0];
}
}
forbids[g] = false;
assert(qtype(nw) != -1);
if(qtype(nw) != -1) printf("%d\n", nw);
return 0;
}
else
{
flag = true;
forbids[g] = false;
continue;
}
}
pair<int, unsigned long long> Z{0, {}};
// printf("X = {%llu}\n", X[0]);
// printf("Y.size() = %lu\n", Y.size());
for(const auto &x : Y)
{
// printf("x = {first = %d, second = {%llu, %llu}}\n", x.first, x.second[0], x.second[1]); fflush(stdout);
if(x.second != X)
{
if(Z.first)
{
flag = true;
break;
}
Z = x;
}
}
if(flag)
{
forbids[g] = false;
continue;
}
if(Z.first == 0)
{
forbids[g] = false;
assert(qtype(g) != -1);
if(qtype(g) != -1) printf("%d\n", g);
}
else
{
int lst = g, nw = Z.first;
while(web[nw].size() == 2)
{
if(web[nw][0] == lst)
{
lst = nw;
nw = web[nw][1];
}
else
{
lst = nw;
nw = web[nw][0];
}
}
forbids[g] = false;
assert(qtype(nw) != -1);
if(qtype(nw) != -1) printf("%d\n", nw);
}
return 0;
// forbids[g] = false;
}
printf("%d\n", -1);
return 0;
}
// 笑点解析:调试这题代码的时候控制台一直在用 1252F 的代码,**并且通过了两个样例**。
// 鉴定为:机关算尽太聪明 写成了一坨石山

其实是推箱子。

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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
/*
O: Player
X: Box (not on target)
Y: Box (on target)
.: Target with no box
#: Wall
: blank

0-indexed

VIM-style move :)
h: left
j: down
k: up
l: right
*/
#include <cstdio>
#include <string>
#include <vector>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <unistd.h>
#include <algorithm>
#include <termios.h>

using namespace std;

class level
{
public:
int n, m, x, y;
vector<basic_string<bool>> wall;
vector<basic_string<bool>> box;
vector<basic_string<bool>> target;
};

int main(int argc, char *argv[])
{
vector<string> names;
if(argc == 1)
{
fprintf(stderr, "No level!\n");
return 1;
}
for(int i=1;i<argc;i++)
{
names.push_back(argv[i]);
}
vector<level> lvls;
for(const string &x : names)
{
ifstream fs(x);
int t;
fs >> t;
// printf("t = %d\n", t);
while(t--)
{
int n, m;
fs >> n >> m;
lvls.push_back({n, m, -1, -1, {}});
string buf;
getline(fs, buf);
int cbox = 0, ctarget = 0;
for(int i=0;i<n;i++)
{
// printf("i = %d\n", i);
getline(fs, buf);
if(buf.size() != m)
{
// printf("%s!\n", buf.c_str());
fprintf(stderr, "File %s Invalid!\n", x.c_str());
return 2;
}
basic_string<bool> wall, box, target;
for(int j=0;j<m;j++)
{
switch(buf[j])
{
case 'O': wall += false; box += false; target += false; if(lvls.back().x == -1) { lvls.back().x = i; lvls.back().y = j; } else { fprintf(stderr, "File %s Invalid!\n", x.c_str()); return 2; } break;
case 'X': wall += false; box += true; target += false; cbox++; break;
case 'Y': wall += false; box += true; target += true; cbox++; ctarget++; break;
case '.': wall += false; box += false; target += true; ctarget++; break;
case '#': wall += true; box += false; target += false; break;
case ' ': wall += false; box += false; target += false; break;
default: fprintf(stderr, "File %s Invalid!\n", x.c_str()); return 2; break;
}
}
lvls.back().wall.push_back(wall);
lvls.back().box.push_back(box);
lvls.back().target.push_back(target);
}
if(cbox != ctarget || cbox == 0)
{
fprintf(stderr, "File %s Invalid!\n", x.c_str());
return 2;
}
}
}
termios ol, rw;
tcgetattr(STDIN_FILENO, &ol);
rw = ol;
rw.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &rw);
for(int id=0;id<lvls.size();id++)
{
level bw = lvls[id];
int x = bw.x, y = bw.y;
auto genmap = [&]() -> string
{
string res = "Level #" + to_string(id + 1);
for(int i=0;i<bw.n;i++)
{
res += "\n";
for(int j=0;j<bw.m;j++)
{
int stat = (int(bw.wall[i][j]) << 2) | (int(bw.box[i][j]) << 1) | int(bw.target[i][j]);
if(i == x && j == y)
{
res += 'O';
continue;
}
switch(stat)
{
case 0: res += ' '; break;
case 2: res += 'X'; break;
case 3: res += 'Y'; break;
case 1: res += '.'; break;
case 4: res += '#'; break;
default: fprintf(stderr, "Internal Error.\n"); tcsetattr(STDIN_FILENO, TCSANOW, &ol); exit(4);
}
}
}
return res;
};
auto proceedmove = [&](char op) -> void
{
int dx, dy;
switch(op)
{
case 'h': dx = 0; dy = -1; break;
case 'j': dx = 1; dy = 0; break;
case 'k': dx = -1; dy = 0; break;
case 'l': dx = 0; dy = 1; break;
case 'r': bw = lvls[id]; x = bw.x; y = bw.y; break;
default: return; // Invalid move
}
if(x + dx < 0 || x + dx >= bw.n || y + dy < 0 || y + dy >= bw.m) return; // Invalid move * 2
if(bw.wall[x + dx][y + dy]) return; // Invalid move * 3
if(!bw.box[x + dx][y + dy])
{
x += dx;
y += dy;
return; // Valid move
}
else if(x + 2 * dx < 0 || x + 2 * dx >= bw.n || y + 2 * dy < 0 || y + 2 * dy >= bw.m) return; // Invalid push
else if(bw.wall[x + 2 * dx][y + 2 * dy] || bw.box[x + 2 * dx][y + 2 * dy]) return; // Invalid push * 2
else
{
bw.box[x + 2 * dx][y + 2 * dy] = true;
bw.box[x + dx][y + dy] = false;
x += dx; y += dy; // Valid push
}
};
auto finished = [&]() -> bool
{
for(int i=0;i<bw.n;i++)
{
for(int j=0;j<bw.m;j++)
{
if(bw.box[i][j] ^ bw.target[i][j]) return false;
}
}
return true;
};
while(!finished())
{
printf("\033[2J\033[H%s", genmap().c_str());
proceedmove(getchar());
}
printf("\033[2J\033[H%s", genmap().c_str());
printf("\nCongratulations! Press any key to go to the next level...\n");
getchar();
}
printf("\033[2J\033[H");
printf("Congratulations! You win all the levels!\n");
tcsetattr(STDIN_FILENO, TCSANOW, &ol);
return 0;
}

C

诶,有点技术含量的 C!

首先发现俄罗斯方块状物的消除是假的。你只需要查询的时候给阈值加上 $\min$ 即可。

数据结构学傻了:

你用一个可删堆维护所有 cnt,同时树状数组维护 cnt 的个数即可。

聪明人:

双指针状物维护 $\min$,直接数组求后缀和。

D

是个人都知道,解存在等价于出现次数最多的字符不超过 $\left\lceil\dfrac{n}{2}\right\rceil$ 次。

怎么构造方案。

我们要使得上面的判断条件始终被保持。那显然我们每次选择出现次数最大值对应字符,对其出现次数 $-1$。

等等有问题,可能连续两次都一样。不过这个好办,$\max$ 不行就次大值。容易证明这个是对的。

E

显然操作顺序不影响。那我们不妨 DFS。

对于每个结点,显然松鼠能够选择的数字个数是容易计算的。此时组合数计算贡献即可。

等下怎么组合数?预处理阶乗?显然不行。卢卡斯?更不行了。其实有一种非常朴素的办法,绝大多数情况下时间复杂度很劣,但是在这道题中可以用。就是考虑它的阶乗展开式,然后得到 $\dbinom{n}{m}=\dfrac{n-m+1}{m}\dbinom{n}{m-1}$。这样迭代 $m$ 次就行了。

对于这道题,考虑 $m$ 其实就是 $D$,然后它的和是由保证的,做完了。复杂度 $O(n\log n)$。其实预处理逆元可以做到线性,懒得写。

1
2
3
#define a auto
#define t return
int main(){a r=[]<a c>(a f,a l,a k){if constexpr(c)t l(f.template operator()<c-1>(f,l,k));else t l(k);};t r.operator()<99>(r,[](a g){t[g](a...k){t g(k...,k...);};},[](a x){t[x](a...y){t x(x,y...);};}([](a f,a s,a...x){t s+f(f,x...);}))(1);}

欢迎 codegolf

racket.cpp(主程序)

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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>
#include <chrono>
#include <filesystem>
#include <fstream>

using namespace std;

int sstm(const string &str) { return system(str.c_str()); }

bool do_compile(const string &x, const string &arg)
{
const auto compute_checksum = [&]()
{
sstm("sha256sum ./" + x + ".cpp > ./" + x + ".hash");
ofstream("./" + x + ".hash", ios_base::app) << arg;
};
if(filesystem::exists("./" + x + ".hash.bak"))
{
compute_checksum();
if(!sstm("./mydiff ./" + x + ".hash ./" + x + ".hash.bak"))
{
filesystem::remove("./" + x + ".hash");
// printf("Hash is the same. do not compile.\n");
return true;
}
if(sstm("g++ " + arg + " ./" + x + ".cpp -o ./" + x))
{
filesystem::remove("./" + x + ".hash");
// printf("Failed when compiling %s.cpp.\n", x.c_str());
return false;
}
filesystem::remove("./" + x + ".hash.bak");
filesystem::rename("./" + x + ".hash", "./" + x + ".hash.bak");
}
else
{
if(sstm("g++ " + arg + " ./" + x + ".cpp -o ./" + x))
{
printf("Failed when compiling %s.cpp.\n", x.c_str());
return false;
}
compute_checksum();
filesystem::rename("./" + x + ".hash", "./" + x + ".hash.bak");
}
return true;
}

class argument
{
public:
bool valid;
vector<string> names;
string validator;
string comparg;
unsigned long long tl;
bool get(const vector<string> &vs)
{
names.clear();
tl = (unsigned)-1; // 1s
valid = true;
for(const string &x : vs)
{
if(x.substr(0, 6) == "-time=")
{
string num = x.substr(6);
if(num.empty() || num.size() > 10 || (unsigned)tl + 1 != 0)
{
valid = false;
return false;
}
tl = 0;
for(char ch : num)
{
if(ch >= '0' && ch <= '9') tl = tl * 10 + (ch - '0');
else
{
valid = false;
return false;
}
if(tl >= 4294967296)
{
valid = false;
return false;
}
}
if(tl == 0)
{
valid = false;
return false;
}
}
else if(x.substr(0, 11) == "-validator=")
{
string nm = x.substr(11);
if(nm.empty() || !validator.empty())
{
valid = false;
return false;
}
validator = nm;
}
else if(x.substr(0, 9) == "-comparg=")
{
string nm = x.substr(9);
if(nm.empty() || !comparg.empty())
{
valid = false;
return false;
}
comparg = nm;
}
else names.push_back(x);
}
if(names.empty())
{
valid = false;
return false;
}
if(names.size() == 1) names.push_back(names[0] + "-sol");
if(comparg.empty()) comparg = "-std=c++26 -Ofast -march=native -pipe";
return true;
}
};

int main(int argc, char *argv[])
{
vector<string> args;
for(int i=1;i<argc;i++)
{
args.push_back(argv[i]);
}
argument arg;
if(!arg.get(args))
{
printf("\033[31mILLEGAL ARGUMENT.\n\033[0mDo pressure test.\n");
printf(R"(Usage:
racket <NAME>... [options]
Options:
-time=<timelimit> An integer which sets the time limit of the problem (ms). Should be in [1, 4294967296). Default unlimited.
-validator=<name> The name of the validator. No '.cpp'
-comparg=<argument> Arguments for compiling. Default -std=c++26 -Ofast -march=native -pipe.
Should be at least 1 name. If there's only one, will use <NAME>.cpp and <NAME>-sol.cpp. Otherwise, will use all the <NAME>.cpp.
)");
return 1;
}
printf("[log] Compile mydiff.cpp\n");
if(!do_compile("mydiff", "-Ofast -march=native -pipe"))
{
printf("\033[31mError when compiling mydiff.cpp. You careless naughty boy.\n\033[0m");
return 2;
}
printf("[log] Compile maker.cpp\n");
if(!do_compile("maker", arg.comparg))
{
printf("\033[31mError when compiling maker.cpp\n\033[0m");
return 4;
}
if(!arg.validator.empty())
{
printf("[log] Compile %s.cpp as validator\n", arg.validator.c_str());
if(!do_compile(arg.validator, arg.comparg))
{
printf("\033[31mError when compiling %s.cpp\n\033[0m", arg.validator.c_str());
return 8;
}
}
for(const string &x : arg.names)
{
printf("[log] Compile %s.cpp\n", x.c_str());
if(!do_compile(x, arg.comparg))
{
printf("\033[31mError when compiling %s.cpp\n\033[0m", x.c_str());
return 16;
}
}
unsigned long long cnt = 0;
bool flag = true;
do
{
printf("Trial #%llu\n", ++cnt);
printf("[log] Execute maker\n");
if(sstm("./maker > ./data.in"))
{
printf("\033[31mmaker raised a runtime error.\n\033[0m");
return 32;
}
for(const string &x : arg.names)
{
printf("[log] Execute %s\n", x.c_str());
auto bgn = chrono::high_resolution_clock::now();
if(int res = sstm("./" + x + " < data.in > " + x + ".out"))
{
printf("%s returned %d\nData #%llu: \033[34mRuntime Error\n\033[0m", x.c_str(), res, cnt);
return 0;
}
auto thyme = chrono::high_resolution_clock::now() - bgn;
if(thyme > chrono::milliseconds(arg.tl + 10))
{
printf("\033[34m%s used %lu ms\n\033[0m", x.c_str(), chrono::duration_cast<chrono::milliseconds>(thyme).count());
return 0;
}
else if(thyme > chrono::milliseconds(arg.tl)) printf("\033[33m[log] %s used %lu ms. Good luck.\n\033[0m", x.c_str(), chrono::duration_cast<chrono::milliseconds>(thyme).count());
else printf("[log] %s used %lu ms\n", x.c_str(), chrono::duration_cast<chrono::milliseconds>(thyme).count());
}
for(int i=0;i+1<arg.names.size();i++)
{
printf("[log] Compare %s.out and %s.out\n", arg.names[i].c_str(), arg.names[i+1].c_str());
if(sstm("./mydiff ./" + arg.names[i] + ".out ./" + arg.names[i] + ".out"))
{
printf("[log] Different.\n");
flag = false;
break;
}
}
} while(flag);
printf("Data #%llu: \033[34mAnswer different.\n\033[0m", cnt);
return 0;
}

mydiff.cpp(辅助)

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
// TODO: Optimize the speed.
#include <cstdio>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main(int argc, char *argv[])
{
if(argc != 3)
{
fprintf(stderr, "Error 1.\n");
return 2;
}
string a = argv[1], b = argv[2];
ifstream x(a), y(b);
if(!x.is_open())
{
fprintf(stderr, "Cannot open %s\n", argv[1]);
return 4;
}
if(!y.is_open())
{
fprintf(stderr, "Cannot open %s\n", argv[2]);
return 8;
}
vector<string> v1, v2;
string now;
while(getline(x, now)) v1.push_back(now);
while(getline(y, now)) v2.push_back(now);
for(string &g : v1) while(!g.empty() && g.back() == ' ') g.pop_back();
for(string &g : v2) while(!g.empty() && g.back() == ' ') g.pop_back();
while(!v1.empty() && v1.back().empty()) v1.pop_back();
while(!v2.empty() && v2.back().empty()) v2.pop_back();
if(v1 == v2) return 0;
return 1;
}

闲话

$T=10^3,K=10^9$ 答案还不到 $600$。就算 $K=10^{18}$,答案也只有约 $815$。所以,事实上这样的策略没什么用。不过,$T=10,K=10^4$ 答案就来到了接近 $10$,所以如果数据点比较少那也是可以的。

观察大样例是更好的办法,万一就算是多测输出也全是 No 呢。


首先这个样例是拿来搞笑的。$T$ 减少 $1$,最终答案增加 $1$ 即可。

容易发现单次测试结果是二项分布。即,得到 $i$ 的概率是 $\dfrac{\dbinom{T}{i}}{2^T}$。

首先,显然最优策略是,对于每一个“当前剩余可操作次数”都有一个阈值 $g_i$,如果这一次得分 $\ge g_i$ 就停下,否则就继续。显然 $g_1=0$。

我们受到了启发。我们设 $f_i$ 为剩余 $i$ 次操作的最大得分。显然有 $f_1=\dfrac{T}{2}$,而 $f_i=\max\limits_{0\le j\le T} X_j+Y_jf_{i-1}$,其中 $X_j$ 代表 $\ge j$ 分的情况下得分的期望(这样表述可能有些问题,严格来讲还要乘上 $\ge j$ 分的概率。不过也可以认为是,进行一次尝试,如果得分 $<j$ 则令得分为 $0$ 的得分的期望),而 $Y_j$ 代表得分 $<j$ 的概率。

这两者都是好求的,前后缀和即可。

同时,我们发现 $X$ 是单降的,$Y$ 是单增的。这样,随着 $f$ 的增长,$\max$ 对应的 $j$ 也是单调不降的(因为 $X$ 越来越不重要,而 $Y$ 越来越重要)。

双指针能够做到 $O(T+K)$,听说洛谷神机能跑过(为什么数据范围不开到 $K\le 10^{18}$?正解这题最大点只跑了 $5\mathrm{ms}$ 欸)。我没试。我是有素质的小朋友。

我们考虑什么时候进行什么决策。显然,是先有一段进行 $j=1$ 的决策,然后 $j=2$ 更优时立马切换到 $j=2$,然后更优时切换到 $j=3$,以此类推。这里所有段都可以为空。显然 $j=k$ 和 $j=k+1$ 的分界线是一个数,大于这个数就后者更优。二分出这个界。

然后对于每一个 $j$,二分出转移次数即可。至于转移,矩阵快速幂。

时间复杂度 $O(T\log^2 K)$。这题数据范围是拿来搞笑的,还是放暴力过的?

另外还有个事,矩阵快速幂可以用对角化替代,直接浮点数 pow 即可。可以少一个 $\log$。我懒得算了,大家加油。

rec&code

rec。

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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/*
样例是拿来搞笑的

你就不考虑样例

考虑暴力。

首先容易发现,得分是一个【二项分布】

然后,对于第 i 次,你有一个值 val[i],代表

- 如果得分 >= val[i],就停止
- 否则,就继续。

显然,val 必须是单调不增的。

那么设 f[i] 为最优的 val[i],g[i] 为最优的期望得分。

边界条件?f[n] = 0, g[n] = n/2.

转移?

如果 f[i] = j, 那么我们有期望得分 [>= j 的概率] * [>= j 的期望分数] + [< j 的概率] * g[i+1]

g[i] = max_j X[j] + Y[j] * g[i+1]. 其中, X[j] 和 Y[j] 是常量。

矩阵说是?

这个讨厌的又有 max 又有 + 又有 * 的式子非常讨厌。

【讨厌的式子非常讨厌】.jpg

还有性质就是说,X 是单调递减的,Y 是单调递增的。

嗯那就是说……这个 max 里面的东西是……单峰的?或者,是凸的?

那你就可以二分出位置了。

然而,更进一步地……最优的 j 随着 g[i+1] 的增长是单调递增的

我们就可以二分出每个 j 接受的转移的 g[i+1] 的最小和最大值。

那这样的话……

嗯太对了。

那这样说矩阵乘法的唯一用处就是辅助进行 dp 了。
*/
#include <cstdio>
#include <algorithm>

using namespace std;


class m2b { public: long double a, b, c, d; m2b(long double _a = 1, long double _b = 0, long double _c = 0, long double _d = 1) : a(_a), b(_b), c(_c), d(_d) {} friend m2b operator*(const m2b &x, const m2b &y) { return {x.a * y.a + x.b * y.c, x.a * y.b + x.b * y.d, x.c * y.a + x.d * y.c, x.c * y.b + x.d * y.d }; }};

m2b qpow(m2b x, unsigned long long y)
{
m2b ans;
do
{
if(y & 1) ans = ans * x;
x = x * x;
} while(y >>= 1);
return ans;
}
long double kdp(long double X, long double Y, long double g, long long k)
{
auto res = qpow({1, 0, X, Y}, k);
// printf("[kdp] X = %.10Lf, Y = %.10Lf, g = %.10Lf, k = %lld. res = {a = %.10Lf, b = %.10Lf, c = %.10Lf, d = %.10Lf}\n", X, Y, g, k, res.a, res.b, res.c, res.d);
return res.c + res.d * g;
}

long double maxj[1005];
long double X[1005], Y[1005], ls[1005], rs[1005], prs[1005];
long double prob[1005];

int main()
{
long long t, k;
scanf("%lld%lld", &t, &k);
t--;
prob[0] = 1;
for(int i=1;i<=t;i++) prob[0] /= 2;
for(int i=1;i<=t;i++) prob[i] = prob[i-1] * (t - i + 1) / i;
for(int i=0;i<=t;i++) ls[i] = (i ? ls[i-1] : 0) + prob[i];
for(int i=t;i>=0;i--) rs[i] = rs[i+1] + prob[i];
for(int i=t;i>=0;i--) prs[i] = prs[i+1] + i * prob[i];
for(int i=0;i<=t;i++) X[i] = prs[i];
for(int i=1;i<=t+1;i++) Y[i] = ls[i-1];
// printf("X[%d] = %Lf, Y[%d] = %Lf\n", 0, X[0], t+1, Y[t+1]);
for(int i=1;i<t;i++)
{
// 二分出 i 对应的最大值
long double l = 0, r = t;
while(r - l > 1e-9)
{
long double mid = (l + r) / 2;
if(X[i] + Y[i] * mid > X[i+1] + Y[i+1] * mid) l = mid;
else r = mid;
}
maxj[i] = l;
// printf("maxj[%d] = %.10Lf\n", i, maxj[i]);
// printf("X[%d] = %.10Lf, Y[%d] = %.10Lf\n", i, X[i], i, Y[i]);
}
maxj[t] = t + 1;
long double g = 1.0L * t / 2;
long long lst = 1;
for(int i=1;i<=t;i++)
{
if(maxj[i] < g) continue;
if(lst == k) break;
if(i == t)
{
// printf("%d: %d times.\n", i, k - lst);
g = kdp(X[i], Y[i], g, k - lst);
continue;
}
int l = 0, r = k - lst - 1;
while(l < r)
{
int mid = (l + r + 1) / 2;
if(kdp(X[i], Y[i], g, mid) <= maxj[i]) l = mid;
else r = mid - 1;
}
l++;
g = kdp(X[i], Y[i], g, l);
// printf("%d: %d times. now g = %.10Lf\n", i, l, g);
lst += l;
}
printf("%.10Lf\n", g + 1);
return 0;
}

显然先考虑 $T=0$。

这个“步数最小”没有任何用,只是规定了必须 DFS。

显然考虑如果我们一棵子树拖延了 $1$ 单位时间,那么它的贡献会增加子树内所有节点的权值之和。

DFS 唯一要考虑的就是子节点的遍历顺序。我们考虑最优的遍历顺序,那显然要先考虑一种顺序的权值。

  • 首先有子树内部的权值,也就是 $\displaystyle\sum_v f_v$(因为这是树形 dp,显然 $v$ 是指 $u$ 的子节点)。这个是不变的。
  • 然后有前面的子树让后面的子树拖延的权值。也就是 $\displaystyle\sum_{i=0}^{\lvert v\rvert-1} (P_{i-1}+2i+1)S_{v_i}$,其中 $P_i=\displaystyle\sum_j^i s_{v_j}$,其中 $s_k$ 是 $k$ 的子树大小的两倍,而 $S_j$ 为 $j$ 的子树权值和。
    • 我们把它拆开。首先,括号里的 $+1$ 直接提出去,变成 $\sum S_v$。然后这个 $2i$ 我们合并到 $P$ 中,令所有 $s$ 加 $2$ 即可。

那就是,我们要最小化 $\displaystyle\sum_{i=0}^{\lvert v\rvert - 1} P_{i-1}S_{v_i}$。

这个看起来很可做,但是瞪一会儿可能没什么头绪。你能够发现,可以看作一项求前面项的贡献,也可以看作前面的项给后面的项提供贡献。同时,贡献具有局部性,并且是有规律的。此时可以考虑 Exchange Argument。

我们不妨设这个 $s$ 为 $X$,$S$ 为 $Y$。那么如果我们有两个元素 $(X_1,Y_1)$ 和 $(X_2,Y_2)$,前者放在后者之间则会多出 $X_1Y_2$ 的贡献,否则会多出 $X_2Y_1$ 的贡献。如果前者放在后者之前是最优解,则必然需要满足 $X_1Y_1\le X_2Y_1$,也就是 $\dfrac{X_1}{Y_1}\le \dfrac{X_2}{Y_2}$。

我们按照 $\dfrac{X}{Y}$ 从小到大排序即可。

做完了,时间复杂度 $O(n\log n)$。

接下来考虑 $T=1$。此时只有一条链不会被走,就是从某个叶子节点回到根节点的路径。是哪个叶子节点?显然,是最深的。注意可能有多个。

我们接着考虑 dp 出一个 $g$,满足在总步数最小的情况下,某个节点的子树的最小权值之和。

这个 $g$ 和 $f$ 的转移几乎一样。只是,需要有一个子节点,它包含当前子树中深度最大的叶子,并且它需要最后被遍历。

你光凭直觉都能感觉到,最后遍历一个节点等价于直接在原本的最优顺序中去掉这个节点再加到最后。事实上也是,用 Exchange Argument 依然可以证明。

不能暴力,因为可能有很多都是可能的最后一个节点(最大值不唯一)。但是这些贡献是容易快速计算的,预处理前缀和即可。

注意还需要用被替换节点的 $g$ 代替 $f$。

时间复杂度没变,还是 $O(n\log n)$。

rec&code

rec。

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
/*
T=0:

考虑如果我拖延了 1 单位时间,则消耗的代价就要加上这个子树内所有权值之和。

转化为如下问题:你有一个二元组序列 (x1, y1), (x2, y2), ..., (xn, yn),重排之

使得 sum(yi * sumprexi) 最小。

考虑局部调整。

x | a b
y | c d

=> 多出 ad 的贡献。

反过来,多出 bc 的贡献。

所以有 ad <= bc, 换句话说,a/c <= b/d。

按照 x/y 从小到大排序即可。

样例正确。

T=1:

停留在哪个节点 有限制。必须是深度最大的节点。

dp 出【需要回来的代价】和【不需要回来的代价】。
*/
#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;

const auto U = [](auto x) { return [x](auto ...y) { return x(x, y...); }; };

int p[200005];
long long a[200005];
vector<int> ch[200005];
unsigned __int128 x[200005], y[200005], dp[200005], dp2[200005];
int dep[200005];

int main()
{
int n, t;
scanf("%d%d", &n, &t);
for(int i=2;i<=n;i++)
{
scanf("%d%lld", p + i, a + i);
ch[p[i]].push_back(i);
}
U([&](auto &&self, int u) -> void
{
if(ch[u].empty())
{
y[u] = a[u];
dp[u] = dp2[u] = 0;
return;
}
y[u] = a[u];
int mxdep = 0;
for(int v : ch[u])
{
self(self, v);
mxdep = max(mxdep, dep[v]);
x[v] += 2;
x[u] += x[v];
y[u] += y[v];
dp[u] += dp[v] + y[v];
}
dep[u] = mxdep + 1;
sort(ch[u].begin(), ch[u].end(), [&](int a, int b) { return x[a] * y[b] < x[b] * y[a]; });
vector<unsigned __int128> lsx, rsy; // wait, rsy? It means right sum of y
for(int i=0;i<ch[u].size();i++)
{
// printf("ch[%d][%d] = %d\n", u, i, ch[u][i]);
dp[u] += (i ? lsx.back() : 0) * y[ch[u][i]];
lsx.push_back((i ? lsx.back() : 0) + x[ch[u][i]]);
}
for(int i=ch[u].size()-1;i>=0;i--)
{
rsy.push_back((rsy.empty() ? 0 : rsy.back()) + y[ch[u][i]]);
}
reverse(rsy.begin(), rsy.end());
// 删掉一个点能够造成什么影响?
// 那当然是,
// 1) 它自身贡献重新计算 2) 后面所有元素贡献减少 x[i]
// 没啦!
dp2[u] = (unsigned __int128)0-1;
for(int i=0;i<ch[u].size();i++)
{
if(dep[ch[u][i]] == mxdep) dp2[u] = min(dp2[u], dp[u] - (i ? lsx[i-1] : 0) * y[ch[u][i]] + (lsx.back() - x[ch[u][i]]) * y[ch[u][i]] - (i == ch[u].size() - 1 ? 0 : rsy[i+1]) * x[ch[u][i]] - dp[ch[u][i]] + dp2[ch[u][i]]);
}
// printf("dep[%d] = %d\n", u, dep[u]);
})(1);
// printf("%d %llu\n", 2 * n - 2, (unsigned long long)dp[1]);
// printf("%llu\n", (unsigned long long)dp2[1]);
if(t == 0) printf("%d %llu\n", 2 * n - 2, (unsigned long long)dp[1]);
else printf("%d %llu\n", 2 * n - 2 - dep[1], (unsigned long long)dp2[1]);
return 0;
}

注意到奶牛和苹果是对称的。我们让奶牛和苹果配对即可。二分图最大匹配。

首先我们放到平面上,横坐标为位置,纵坐标为时间。

我们考虑苹果和奶牛配对。这是因为,苹果只能向下配对,这样有下限 $x=0$。而虽然奶牛也有上限($x=10^9$),但是需要参与运算,不好考虑。

那么,一个苹果能够匹配到的奶牛的范围:desmos。我不想传图到洛谷图床。

我们首先考虑简化版,所有奶牛都在 $t=0$ 时出现。也就是说,它们都在 $x$ 轴上。此时,每个苹果对应一个区间(启示 $1$)。

我们考虑贪心,按照右端点从小到大排序(启示 $2$)。为什么?

首先贪心是显然的。你不配对相当于没用,不会有好处。

  • 两个区间,相互包含,一个点 $K$ 同时在两个区间中:desmos。此时,如果选择了外面的区间,那可能还有点 $H$ 处于外面的区间中但是不处于内部的区间中。那么我们就应该选择里面的区间,这没有任何坏处。
  • 两个区间,不相互包含,一个点 $K$ 同时在两个区间中:desmos。此时难以判断,但是如果 $K$ 左边的奶牛都已经被配对,或者无法配对了,那么显然选择左边的 $Q$ 更优。也就是说,如果我们从左往右考虑,那么在左边的更优。

综合上述两种情况,按照右端点从左到右排序。对于每个苹果,如果有可以匹配的奶牛,则匹配最靠左的。

现在来考虑原题,不保证奶牛的 $t=0$。

其实差别不大,只需要考虑如何排序和如何判断“靠左”。

对于排序,显然顺序是一样的。如何判断“靠左”?其实这里“靠左”本质上是“不容易和其它奶牛配对”。一个奶牛 $(t,x)$ 和一个苹果 $(T,X)$ 能够配对的充要条件是 $\lvert x-X\rvert \le T-t$,换句话说就是,$t+x\le T+X$ 和 $t-x\ge T-X$……这是什么意思?$[t-x,t+x]\subseteq [T-X,T+X]$。哦对了几何意义也可以证的。

那么,我们既然在按照右端点 $T+X$ 从小到大排序,那么用一个数据结构(如 set)维护“目前满足右界限制的所有点的集合”,只需要判断左界限制即可。

我们按照 $T-X$ 从小到大排序所有奶牛,然后用 std::set 的 lower_bound 方法找到 $\ge T-X$ 的最小奶牛即可。

至于如何加入右端点符合的,这个你扫描线即可。

时间复杂度 $O(n\log n)$。注意如果用 set 那你比较方法不能直接写 $T-X$ 的比较,因为可能这个值相等,然后 set 判断为两个元素等价,只保留一个,你就挂了。用 multiset,或者两者相等时指定一个顺序(比如按照 $X$ 从大到小)即可。

rec&code

rec。

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
// Aaron Catching G
// This is an Aaron. I like Aarons. Aarons are good for our English (and Chinglish).
// 没看到 一旦一头奶牛接住了一个苹果,她就会离开数轴。 见祖宗
/*
考虑贪心

优先考虑【右端点靠左】的苹果,也就是按照 pos + time 从小到大排序。如果相同,则按照 pos 从小到大排序。

匹配的是【靠左】的奶牛。

哪些奶牛可以被匹配?

既然你是右端点越来越大,那你就扫描线,不断加入奶牛即可。

判断左端点合法?

pos >= P - (T - time). 换句话说,pos - time >= P - T

右端点也合法。这是扫描线保证的。pos + time <= P + T

有没有保证 time <= T?显然。这是区间长度。
*/
#include <cstdio>
#include <set>
#include <algorithm>

using namespace std;

class appon // apple & aaron
{
public:
long long t, x;
mutable long long k;
} apple[200005], aaron[200005] /* cow */;

int main()
{
int n;
scanf("%d", &n);
int x = 0, y = 0;
for(int i=1;i<=n;i++)
{
int q;
scanf("%d", &q);
if(q == 1)
{
x++;
scanf("%d%d%d", &aaron[x].t, &aaron[x].x, &aaron[x].k);
}
else
{
y++;
scanf("%d%d%d", &apple[y].t, &apple[y].x, &apple[y].k);
}
}
sort(apple + 1, apple + y + 1, [](const auto &x, const auto &y) { return x.t + x.x < y.t + y.x || x.t + x.x == y.t + y.x && x.x < y.x; });
sort(aaron + 1, aaron + x + 1, [](const auto &x, const auto &y) { return x.t + x.x < y.t + y.x || x.t + x.x == y.t + y.x && x.x < y.x; });
class _
{
public:
bool operator()(const appon &x, const appon &y) const { return x.x - x.t < y.x - y.t || x.x - x.t == y.x - y.t && x.x > y.x; }
};
set<appon, _> st;
int cur = 0;
long long sum = 0;
for(int i=1;i<=y;i++)
{
while(cur < x && aaron[cur + 1].t + aaron[cur + 1].x <= apple[i].t + apple[i].x) st.insert(aaron[++cur]);
while(apple[i].k && !st.empty())
{
auto it = st.lower_bound(apple[i]);
if(it == st.end()) break;
sum += min(apple[i].k, it->k);
// printf("apple {t = %d, x = %d, k = %d} <---> aaron {t = %d, x = %d, k = %d}\n", apple[i].t, apple[i].x, apple[i].k, it->t, it->x, it->k);
if(it->k == apple[i].k)
{
st.erase(it);
break;
}
if(it->k > apple[i].k)
{
it->k -= apple[i].k;
break;
}
apple[i].k -= it->k;
st.erase(it);
}
}
printf("%lld\n", sum);
return 0;
}
// Lionblaze 危
0%