为什么鸽笼原理总会以一种奇怪的方式出现在时间复杂度分析中 /youl
暴力模拟是 的,且看上去并没有多大的优化空间 /ng
不妨先考虑 S 的情况。设第 个学生最终取到的蔬菜的营养值为 ,此时我们每插入一个 , 发生的变化形如:
- 按 从前到后扫一遍 。
- 若 ,我们可以不选择 转而选择 、如果原 在后面有用还可以留给后面。
- 于是我们此时 即可。
- 不难发现扫到最后会剩下一个 ,显然这个数后面都用不到了,将其加入答案。
考虑将其扩展到一般情况,不难发现我们只需要根据 是啥决定符号是 即可。时间复杂度为 。
注意到对于一个 相等的段,数集的变化是:
- 若
S,当 ,用 替换 。 - 若
B,当 ,用 替换 。
把连续段缩起来,用堆维护即可。时间复杂度为 。甚至比刚刚那个东西更劣了 /ng
人类智慧地,注意到对于两个相邻的 S/B 连续段,若前者的 大于后者的 ,则讨论一下可以发现这两个段交换后无影响,于是我们可以通过交换再把相邻且 相同的连续段缩起来。
然后你发现这样写就直接过了,下面我们来分析一下时间复杂度:
- 设一开始的连续段为 (忽略两端的 段)。
- 由于 ,则根据鸽笼原理,一定存在 个 ,使得 。
- 设有势能 表示 中 的元素个数加上 中 的元素个数,则讨论一下可得每操作一次 , 至少减少 。
- 在 次操作后,每个位置 有三种情况:自己势能归零而被交换、 被交换、 被交换。
- 于是第一种情况的次数总和必然 ,则此时 至少会减少至 。
- 设 表示 给定时的时间复杂度,则 ,解得 。
于是时间复杂度为 。
代码:
#include <iostream>
#include <cstdio>
using namespace std;
typedef long long ll;
typedef struct {
int ls;
int rs;
int dis;
int val;
} Node;
const int mod = 1e9;
int id = 0;
int a[200007], b[200007], cnt[7], type[7][200007], root[7][200007];
char s[200007];
Node tree[22000007];
inline int new_node(int x){
id++;
tree[id].dis = 1;
tree[id].val = x;
return id;
}
int merge(int type, int x, int y){
if (x == 0) return y;
if (y == 0) return x;
if ((type == 0) == (tree[x].val > tree[y].val)) swap(x, y);
tree[x].rs = merge(type, tree[x].rs, y);
if (tree[tree[x].ls].dis < tree[tree[x].rs].dis) swap(tree[x].ls, tree[x].rs);
tree[x].dis = tree[tree[x].rs].dis + 1;
return x;
}
inline void push(int type, int &x, int k){
x = merge(type, x, new_node(k));
}
inline void pop(int type, int &x){
x = merge(type, tree[x].ls, tree[x].rs);
}
int main(){
int n, m;
ll last_ans = 0;
scanf("%d", &n);
for (register int i = 1; i <= n; i++){
scanf("%d", &a[i]);
}
scanf("%d", &m);
for (register int i = 1; i <= m; i++){
scanf("%d", &b[i]);
}
scanf("%s", &s[1]);
for (register int i = 1; i <= m; ){
int nxt = i;
while (nxt < m && s[i] == s[nxt + 1]) nxt++;
type[0][++cnt[0]] = s[i] == 'S' ? 0 : 1;
for (register int j = i; j <= nxt; j++){
push(type[0][cnt[0]], root[0][cnt[0]], b[j]);
}
i = nxt + 1;
}
for (register int i = 1; i <= n; i++){
int cur = i & 1, pre = cur ^ 1;
a[i] = (int)((a[i] + last_ans) % mod);
for (register int j = 1; j <= cnt[pre]; j++){
int x = tree[root[pre][j]].val;
if ((type[pre][j] == 0) == (a[i] > x)){
pop(type[pre][j], root[pre][j]);
push(type[pre][j], root[pre][j], a[i]);
a[i] = x;
}
}
last_ans += a[i];
cout << last_ans << " ";
cnt[cur] = 0;
for (register int j = 1; j <= cnt[pre]; j++){
if (cnt[cur] == 0){
cnt[cur]++;
type[cur][cnt[cur]] = type[pre][j];
root[cur][cnt[cur]] = root[pre][j];
} else if (type[cur][cnt[cur]] == type[pre][j]){
root[cur][cnt[cur]] = merge(type[pre][j], root[cur][cnt[cur]], root[pre][j]);
} else if (cnt[cur] > 1 && (type[cur][cnt[cur]] == 0) == (tree[root[cur][cnt[cur]]].val > tree[root[pre][j]].val)){
root[cur][cnt[cur] - 1] = merge(type[pre][j], root[cur][cnt[cur] - 1], root[pre][j]);
} else {
cnt[cur]++;
type[cur][cnt[cur]] = type[pre][j];
root[cur][cnt[cur]] = root[pre][j];
}
}
}
return 0;
}