# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
981048 | nnin | Sequence (APIO23_sequence) | C++17 | 0 ms | 0 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include "sequence.h"
#include<bits/stdc++.h>
using namespace std;
#define pii pair<int,int>
vector<int> ct[500005];
int N;
vector<pii> v;
struct node {
int val;
node *left, *right;
node(int v) {
val = v;
left = right = NULL;
}
};
struct persistTree {
node *root;
void build(node *cur, int l, int r) {
if(l==r) return;
int m = (l+r)/2;
cur->left = new node(0);
cur->right = new node(0);
build(cur->left, l, m);
build(cur->right, m+1, r);
}
void build() {
root = new node(0);
build(root, 0, N-1);
}
void update(node *cur, node *prev, int l, int r, int x) {
if(l==r) {
cur->val++;
return;
}
int m = (l+r)/2;
if(x<=m) {
cur->left = new node(0);
cur->right = prev->right;
update(cur->left, prev->left, l, m, x);
} else {
cur->left = prev->left;
cur->right = new node(0);
update(cur->right, prev->right, m+1, r, x);
}
cur->val = cur->left->val+cur->right->val;
}
void update(node *prev, int x) {
root = new node(0);
update(root, prev, 0, N-1, x);
}
int query(node *add, node *sub, int l, int r, int wl, int wr) {
if(wl>r || wr<l) return 0;
if(wl<=l && wr>=r) return add->val-sub->val;
int m = (l+r)/2;
return query(add->left, sub->left, l, m, wl, wr) + query(add->right, sub->right, m+1, r, wl, wr);
}
int query(node *sub, int wl, int wr) {
if(wr<wl) return 0;
return query(root, sub, 0, N-1, wl, wr);
}
};
vector<persistTree> persist;
bool check(int x) {
for(int i=1;i<=N;i++) {
for(int j=0;j+x-1<ct[i].size();j++) {
int st = ct[i][j];
int en = ct[i][j+x-1];
int q1 = persist[lower_bound(v.begin(), v.end(), make_pair(i, -1))-v.begin()].query(persist[0].root, st+1, en-1);
int q2 = persist[N].query(persist[upper_bound(v.begin(), v.end(), make_pair(i, (int)1e9))-v.begin()].root, st+1, en-1);
if(abs(q1-q2)<=x) return true;
}
}
return false;
}
int sequence(int n, std::vector<int> A) {
N = n;
for(int i=0;i<N;i++) {
ct[A[i]].push_back(i);
v.push_back({A[i], i});
}
sort(v.begin(), v.end());
persist.resize(N+1);
persist[0].build();
for(int i=0;i<N;i++) {
persist[i+1].update(persist[i].root, v[i].second);
}
int l = 1, r = 1;
for(int i=1;i<=N;i++) {
r = max(r, (int)ct[i].size());
}
while(r>1) {
if(check(r)) return r;
r--;
}
return 1;
}