JOI 2016 - Skyscraper
Author: Andi Qu
Time Complexity: .
We will use connected component DP to solve this problem.
First, sort the buildings by height. We will now "insert" them into the final permutation at various positions and count the number of ways to do so.
Let denote the number of ways to insert the first buildings into the permutation such that:
- There were "connected components" (i.e. subarrays with all positions filled).
- The "total cost" (assuming that all empty positions contain , where ) is .
- of the endpoints of the permutation have been filled so far.
For example, (a half-filled permutation of ) would be counted in .
Note that we don't cwere about the relative orders of the connected components for each DP state. (Imagine that they're just free-floating components that we can pluck out of space and join.)
When we transition from to , all the empty positions will change from to , so the change in total cost (given and ) would thus be . Each connected component contributes to except for those containing endpoints, which only contribute .
We now have five cases to consider when calculating :
- We inserted to form a new component that doesn't contain an endpoint of the permutation.
- There were ways to do this.
- We inserted to form a new component that contains an endpoint of the permutation.
- This is only possible if .
- If so, there were ways to do this.
- We appended to an existing component such that it doesn't contain an end of the permutation.
- There were component endpoints to choose from, so there were ways to do this.
- We appended to an existing component such that it contains of the permutation.
- This is only possible if .
- If , then there were component endpoints to choose from, so there were ways to do this.
- If , and , then must hold and so there were ways to do this.
- Otherwise, there were component endpoints to choose from (we can't choose the other component containing an endpoint of the permutation!), so there were ways to do this.
- We inserted to join two existing components.
- If and , then there can only be two components left, so there were ways to do this.
- If otherwise, then there were ordered pairs of components to choose from, so there were ways to do this.
- If , then there were ordered pairs of components to choose from, so there were ways to do this.
- Otherwise, there were ordered pairs of components to choose from, so there were ways to do this.
#include <bits/stdc++.h>typedef long long ll;using namespace std;const ll MOD = 1e9 + 7;int a[102];ll dp[102][102][1002][3];int main() {
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!