题解:CF1322E Median Mountain Range
Claire0918 · · 题解
看到中位数,套路化地想到枚举一个
我们发现一个 01 交替子串
Code:
#include<bits/stdc++.h>
#define mem(a, v) memset(a, v, sizeof(a))
using namespace std;
namespace IO{
#define SIZ (1 << 18)
char ibuf[SIZ], *p1 = nullptr, *p2 = nullptr;
#define gc() (p1 == p2 && (p2 = (p1 = ibuf) + fread(ibuf, 1, SIZ, stdin), p1 == p2) ? EOF : *p1++)
template <typename tp>
void rd(tp &x){
x = 0;
int f = 1;
char c = gc();
for (;!isdigit(c); c == '-' && (f = -1), c = gc());
for (;isdigit(c); x = x * 10 + (c ^ 48), c = gc());
x *= f;
}
template <typename tp, typename... Arg>
inline void rd(tp &x, Arg &...args){
rd(x), rd(args...);
}
char obuf[SIZ], *p3 = obuf;
inline void flush(){
fwrite(obuf, 1, p3 - obuf, stdout), p3 = obuf;
}
inline void pc(const char c){
p3 - obuf == SIZ && (flush(), 1538), *p3++ = c;
}
template <typename tp>
void prt(tp x, char ed = '\n'){
x < 0 && (pc('-'), x = -x);
static char stk[40];
int stkp = 0;
do{
stk[stkp] = char(x % 10), x /= 10, ++stkp;
} while (x);
while (stkp){
pc(char(stk[--stkp] + '0'));
}
pc(ed);
}
#undef gc
#undef SIZ
}
using namespace IO;
const int maxn = 5e5 + 10;
int n, res = 0;
int a[maxn], b[maxn];
vector<int> tmp, ad[maxn];
set<int> st, pos;
inline void calc(int x, int v){
if (st.find(x) == st.end()){
return;
}
if (x > 1){
const int pl = *--st.lower_bound(x), mid = (pl + x - 1 >> 1) + 1;
res = max(res, x - pl - 1 >> 1);
if (a[x - 1]){
for (auto it = pos.lower_bound(mid); it != pos.end() && *it < x; it++, pos.erase(prev(it))){
b[*it] = v;
}
}
}
if (x <= n){
const int pr = *st.upper_bound(x), mid = x + pr - 1 >> 1;
res = max(res, pr - x - 1 >> 1);
if (a[x]){
for (auto it = pos.lower_bound(x); it != pos.end() && *it <= mid; it++, pos.erase(prev(it))){
b[*it] = v;
}
}
}
}
int main(){
rd(n), st.insert(n + 1);
for (int i = 1; i <= n; i++){
rd(a[i]), tmp.push_back(a[i]), st.insert(i), pos.insert(i);
}
sort(tmp.begin(), tmp.end()), tmp.erase(unique(tmp.begin(), tmp.end()), tmp.end());
for (int i = 1; i <= n; i++){
ad[a[i] = lower_bound(tmp.begin(), tmp.end(), a[i]) - tmp.begin() + 1].push_back(i), a[i] = 0;
}
for (int i = 1; i <= tmp.size(); i++){
for (auto x: ad[i]){
a[x] = 1, a[x] == a[x + 1] && (st.insert(x + 1), 1538), a[x] == a[x - 1] && (st.insert(x), 1538);
x < n && a[x] != a[x + 1] && (st.erase(x + 1), 1538), x > 1 && a[x] != a[x - 1] && (st.erase(x), 1538);
}
for (auto x: ad[i]){
calc(*--st.upper_bound(x), i), calc(*st.upper_bound(x), i);
}
}
prt(res);
for (int i = 1; i <= n; i++){
prt(tmp[b[i] - 1], ' ');
}
flush();
return 0;
}