ABC209F Deforestation

Original link: https://blog.chungzh.cn/articles/abc-209f/

ABC209F Deforestation

The meaning of the question: Given the height of $n$ trees, the cost of cutting the $i$th tree is $h_i+h_{i-1}+h_{i+1}$, how many schemes can be cut down? The total cost of all trees is the smallest.


The cost of cutting down a tree is only related to the height of adjacent trees. Next, we study the influence of the order of cutting $h_i$ and $h_{i+1}$ on the answer.

  1. Cut $h_i$ first and then cut $h_{i+1}$: $h_i+h_{i-1}+h_{i+1}+h_{i+1}+h_{i+2}$
  2. Cut $h_{i+1}$ first and then $h_i$: $h_{i+1}+h_i+h_{i+2}+h_i+h_{i-1}$

After making a difference, get: $h_{i+1}-h_i$. When $h_{i+1}>h_i$, $h_{i+1}$ should be cut first. When $h_{i+1}<h_i$, $h_i$ should be cut first. Therefore, for two adjacent trees, the one that is cut first is the best .


Insertion DP (insertion DP) : first consider the first $i-1$ number, and then insert the $i$th number in the middle.

Let $\mathit{f}_{i,j}$ represent the tree-cutting order of the first $i$ trees, and the $i$th tree is ranked at the $j$ position, and the number of solutions with the minimum cost is obtained .

When $h_{i+1} > h_i$, $i+1$ should be cut first, then $\mathit{f} {i+1,j} = \sum {k=j}^{i}\mathit {f}_{i,k}$

When $h_i > h_{i+1}$, $i$ should be cut first, then $\mathit{f} {i+1,j} = \sum {k=1}^{j-1}\mathit {f}_{i,k}$

When $h_i = h_{i+1}$, any tree can be cut, $\mathit{f} {i+1,j} = \sum {k=1}^i\mathit{f}_{i ,k}$

DP can be optimized with prefix sum, $O(n^2)$.

Mental error! : Subtraction forget to add MOD.

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 
 #include <bits/stdc++.h>  
using namespace std ; typedef long long LL ; const LL MOD = 1e9 + 7 ; LL n , h [ 4005 ]; LL dp [ 4005 ][ 4005 ], sum [ 4005 ][ 4005 ]; int main () { cin >> n ; for ( int i = 1 ; i <= n ; i ++ ) cin >> h [ i ]; dp [ 1 ][ 1 ] = sum [ 1 ][ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= i ; j ++ ) { if ( h [ i ] > h [ i - 1 ]) { dp [ i ][ j ] = ( sum [ i - 1 ][ i - 1 ] - sum [ i - 1 ][ j - 1 ] + MOD ) % MOD ; } else if ( h [ i ] < h [ i - 1 ]) { dp [ i ][ j ] = ( sum [ i - 1 ][ j - 1 ]) % MOD ; } else { dp [ i ][ j ] = ( sum [ i - 1 ][ i - 1 ]) % MOD ; } sum [ i ][ j ] = ( sum [ i ][ j - 1 ] + dp [ i ][ j ]) % MOD ; } } LL ans = 0 ; for ( int i = 1 ; i <= n ; i ++ ) ans = ( ans + dp [ n ][ i ]) % MOD ; cout << ans << endl ; return 0 ; }

Thanks to ABC 209 F – Deforestation – hzy0227

This article is transferred from: https://blog.chungzh.cn/articles/abc-209f/
This site is only for collection, and the copyright belongs to the original author.