hldblog

AIIO 2013 Vitamin D Solution

18 Sep 2022

For simplicity, we refer to cell i as the the 1 meter space between the i‘th and i+1‘th metre on the beach. Then, the beach has L cells from 0 to L-1.

We iterate through minutes 1 to N, updating an array called ans, similar to a “streak”. ans[i] is the current “streak” of cell i. Sunlit cells during minute i will have +1 added to their streak, while non-sunlit cells during minute i will have their streak reset to 0. Our answer is the maximum of all the streaks in ans at all possible minutes.

Alternative explanation: Suppose you had a 2d boolean array sun where sun[j][i] is 1 if cell j was sunlit at minute i, 0 otherwise. The ultimate answer (which we output) is the maximum of the answers for any cell j. The answer for any cell j is the length of the longest block of contiguous 1s in sun[j]. Exactly the same as this Leetcode problem. To find this length, we can use a “streak” algorithm (see here). Solving Vitamin D just requires you to apply the streak algorithm in parallel for multiple boolean arrays.

For Subtask 1, you can do this naively:

#include<bits/stdc++.h>
using namespace std;
const int maxl = 1e6+5;
int cnt[maxl];
signed main() {
	//freopen("vit.in", "r", stdin);
	//freopen("vit.out", "w", stdout);
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	int N, L; cin >> N >> L;
	int res = 0;
	for(int i = 1; i <= N; i++) { //minute i
		int a, b; cin >> a >> b; //cells [a, b)
		//reset non sunlit cells
		for(int j = 0; j <= a-1; j++) { 
			cnt[j] = 0;
		}
		for(int j = b; j <= L-1; j++) {
			cnt[j] = 0;
		}
		//add 1 to cnt of all sunlit cells
		for(int j = a; j <= b-1; j++) {
			cnt[j]++;
		}
		//maximum cnt over all minutes
		res = max(res, *max_element(cnt,cnt+L));
	}
	cout << res << '\n';
}

For the full solution notice how every minute we set \(\smash cnt[0\:..\:a_i-1]\) and \(cnt[b_i\:..\:L-1]\) to 0 (range set) and add +1 to \(\smash cnt[a_i\:..\:b_i-1]\) (range add). We then peek at the maximum of cnt. If we convert cnt to a segment tree we can do these operations in O(log L) time every minute. Which yields a total time complexity of O(N log L).

Implementation is left as an exercise to the reader.