USACO Gold 2016 Open - 248
Authors: Melody Yu, Qi Wang, Rohak Debnath
Video Solution
Note: The video solution might not be the same as other solutions. Code in C++.
Explanation
Consider a range . Since elements need to be adjacent to be merged and each new element will originate from a series of merges on a subarray, we can think about the subarrays of .
Let us define as the subarray of (with and inclusive and 0-based) such that is the element that can be merged into as a single element. If it cannot be merged into a single element, let it be (-1). For from to inclusive, we can check for the following transitions:
- If , (base case).
- Otherwise, if and , then .
If we find two equal and adjacent ranges, we can merge them for a value of plus the value of either of the two ranges. It can also be helpful to notice that a range can only merge into a unique number. Hence, it is not necessary to write the transitions as .
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;int main() {freopen("248.in", "r", stdin);int n;cin >> n;vector<int> a(n);for (int i = 0; i < n; i++) { cin >> a[i]; }
Java
import java.io.*;import java.util.*;public class U248 {public static void main(String[] args) throws IOException {Kattio io = new Kattio("248");int N = io.nextInt();int[] board = new int[N];
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!