Table of Contents

SolutionImplementation

Official Analysis (C++)

Solution

This is a similar solution to the official editorial but uses a segment tree for the transitions instead. I highly recommend reading the official editorial in addition to this solution.

Notice the constraints required to make an ordering of stamps valid. There must be at least one segment of length k or longer. We can work backwards starting from this segment. Remove this segment of length kk. Then we can remove the segments to the left and right of it because even if there aren't longer than kk, we can assume that they overlapped with the previous segment we removed. We can remove the whole painting like this.

Now we just need to count the number of orderings with a contiguous segment of length kk with all the same color. Instead of this, we can use complementary counting and count the opposite instead with dynamic programming. Let dp[i]dp[i] be the number of orderings for the first ii characters. When ii is less than kk, dp[i]=midp[i] = m^i since the first ii characters can be any of the mm colors. Notice that we can add a segment of length of up to k1k - 1 of a single color to the end of a valid ordering. This segment can have m1m - 1 colors (we can't choose the color that corresponds to the previous segment because the two segments combined can become longer than kk). Thus, we can state the following recurrences.

If x<kx < k, then dp[x]dp[x] will be mxm^x. Otherwise if x>=kx >= k, then dp[x]dp[x] will be the sum of the last k1k - 1 dpdp states multiplied by m1m - 1. More formally, we can define this relation as: dp[x]=mx if x<kdp[x] = m^x \texttt{ if } x < k

dp[x]=(m1)i=xk+1x1dp[i] if xkdp[x] = (m - 1) \cdot \sum_{i=x-k+1}^{x-1} dp[i] \texttt{ if } x \ge k

To compute the second type of transition, we can use a segment tree. We can subtract dp[n]dp[n] from mnm^n (total number of paintings) to get the number of valid paintings.

Implementation

Time Complexity: O(Nlog(N))\mathcal{O}(N \log(N))

C++

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll MOD = 1e9 + 7;
Code Snippet: Segment Tree (Click to expand)
/**

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!