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 . Then we can remove the segments to the left and right of it because even if there aren't longer than , 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 with all the same color. Instead of this, we can use complementary counting and count the opposite instead with dynamic programming. Let be the number of orderings for the first characters. When is less than , since the first characters can be any of the colors. Notice that we can add a segment of length of up to of a single color to the end of a valid ordering. This segment can have colors (we can't choose the color that corresponds to the previous segment because the two segments combined can become longer than ). Thus, we can state the following recurrences.
If , then will be . Otherwise if , then will be the sum of the last states multiplied by . More formally, we can define this relation as:
To compute the second type of transition, we can use a segment tree. We can subtract from (total number of paintings) to get the number of valid paintings.
Implementation
Time Complexity:
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!