833B - The Bakery - CodeForces Solution


binary search data structures divide and conquer dp two pointers *2200

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define sz(a) ((int) a.size())
#define ls u << 1
#define rs u << 1 | 1
const int N = 1e5 + 15;
int n, k, a[N];
int lt[N], lst[N], dp[N];
int tr[N << 2];
int kp[N << 2];
void push(int u) {
	kp[ls] += kp[u];
	tr[ls] += kp[u];
	tr[rs] += kp[u];
	kp[rs] += kp[u];
	kp[u] = 0; 
}
void build(int u, int l, int r) {
	kp[u] = 0;
	if(l == r) {
		tr[u] = dp[l];
		return;
	}
	int m = (l + r) / 2;
	build(ls, l, m);
	build(rs, m + 1, r);
	tr[u] = max(tr[ls], tr[rs]);
}
int get(int ql, int qr, int u = 1, int l = 0, int r = n) {
	push(u);
	if(ql > qr or ql > r or l > qr) return 0;
	if(ql <= l && r <= qr) return tr[u];
	int m = (l + r) / 2;
	return max(get(ql, qr, ls, l, m), get(ql, qr, rs, m + 1, r)); 
}
void upd(int ql, int qr, int u = 1, int l = 0, int r = n) {
	push(u);
	if(ql > qr or ql > r or l > qr) return;
	if(ql <= l && r <= qr) {
		tr[u] += 1;
		kp[u] += 1;
		return;
	}
	int m = (l + r) / 2;
	upd(ql, qr, ls, l, m);
	upd(ql, qr, rs, m + 1, r);
	tr[u] = max(tr[ls], tr[rs]);
}
int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cin >> n >> k;
	for(int i = 1; i <= n; i++) {
		cin >> a[i];
		lt[i] = lst[a[i]];
		lst[a[i]] = i;
	}
	for(int i = 1; i <= n; i++) dp[i] = -n;
	dp[0] = 0;
	for(int j = 1; j <= k; j++) {
		build(1, 0, n);
		for(int i = 0; i <= n; i++) {
			upd(lt[i], i - 1);
			dp[i] = get(0, i - 1);
		}
	}
	cout << dp[n] << '\n';
}


Comments

Submit
0 Comments
More Questions

714B - Filya and Homework
31A - Worms Evolution
1691A - Beat The Odds
433B - Kuriyama Mirai's Stones
892A - Greed
32A - Reconnaissance
1236D - Alice and the Doll
1207B - Square Filling
1676D - X-Sum
1679A - AvtoBus
1549A - Gregor and Cryptography
918C - The Monster
4B - Before an Exam
545B - Equidistant String
1244C - The Football Season
1696B - NIT Destroys the Universe
1674A - Number Transformation
1244E - Minimizing Difference
1688A - Cirno's Perfect Bitmasks Classroom
219A - k-String
952A - Quirky Quantifiers
451B - Sort the Array
1505H - L BREAK into program
171E - MYSTERIOUS LANGUAGE
630D - Hexagons
1690D - Black and White Stripe
1688D - The Enchanted Forest
1674C - Infinite Replacement
712A - Memory and Crow
1676C - Most Similar Words