USACO Gold 2016 Open - 248

Authors: Melody Yu, Qi Wang, Rohak Debnath

Official Analysis (Java)

Video Solution

Note: The video solution might not be the same as other solutions. Code in C++.

Explanation

Consider a range A[i..j]A[i..j]. 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 A[i..j]A[i..j].

Let us define dp[i][j]dp[i][j] as the subarray of AA (with ii and jj inclusive and 0-based) such that dp[i][j]dp[i][j] 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 kk from ii to j1j-1 inclusive, we can check for the following transitions:

  1. If i==ji == j, dp[i][j]=a[i]dp[i][j] = a[i] (base case).
  2. Otherwise, if dp[i][k]1dp[i][k] \neq -1 and dp[i][k]==dp[k+1][j]dp[i][k] == dp[k+1][j], then dp[i][j]=dp[i][k]+1dp[i][j] = dp[i][k] + 1.

If we find two equal and adjacent ranges, we can merge them for a value of 11 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 dp[i][j]=max(dp[i][j],dp[i][k]+1)dp[i][j] = \max(dp[i][j], dp[i][k] + 1).

Implementation

Time Complexity: O(N3)\mathcal{O}(N^3)

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!