动态规划1 基础

这是系统复习动态规划 (Dynamic Programming, DP)的第一篇随笔.
Codeforces 711 C coloring trees 为例, 总结一下DP的基础知识.

  • time limit per test 2 seconds
  • memory limit per test 256 megabytes
  • input standard input
  • output standard output

ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where $n$ trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from 1 to $n$ from left to right.

Initially, tree $i$ has color $c_i$. ZS the Coder and Chris the Baboon recognizes only $m$ different colors, so $0 le c_i le m$, where $ci = 0$ means that tree i is uncolored.

ZS the Coder and Chris the Baboon decides to color only the uncolored trees, i.e. the trees with $c_i = 0$. They can color each of them them in any of the m colors from 1 to $m$. Coloring the $i$-th tree with color $j$ requires exactly $p_{i, j}$ litres of paint.

The two friends define the beauty of a coloring of the trees as the minimum number of contiguous groups (each group contains some subsegment of trees) you can split all the n trees into so that each group contains trees of the same color. For example, if the colors of the trees from left to right are 2, 1, 1, 1, 3, 2, 2, 3, 1, 3, the beauty of the coloring is 7, since we can partition the trees into 7 contiguous groups of the same color : {2}, {1, 1, 1}, {3}, {2, 2}, {3}, {1}, {3}.

ZS the Coder and Chris the Baboon wants to color all uncolored trees so that the beauty of the coloring is exactly $k$. They need your help to determine the minimum amount of paint (in litres) needed to finish the job.

Please note that the friends can't color the trees that are already colored.
Input

The first line contains three integers, $n$, $m$ and $k$ ($1 le k le n le 100, 1 le m le 100$) — the number of trees, number of colors and beauty of the resulting coloring respectively.

The second line contains $n$ integers $c_1, c_2, cdots, c_n (0 le c_i le m)$, the initial colors of the trees. $c_i$ equals to 0 if the tree number $i$ is uncolored, otherwise the $i$-th tree has color $c_i$.

Then $n$ lines follow. Each of them contains $m$ integers. The $j$-th number on the $i$-th of them line denotes $p_{i, j} (1 le p_{i, j} le 10^9)$ — the amount of litres the friends need to color $i$-th tree with color $j$. $p_{i, j}$'s are specified even for the initially colored trees, but such trees still can't be colored.
Output

Print a single integer, the minimum amount of paint needed to color the trees. If there are no valid tree colorings of beauty $k$, print  - 1.

Examples

Input

3 2 2
0 0 0
1 2
3 4
5 6

Output

10

Input

3 2 2
2 1 2
1 3
2 4
3 5

Output

-1

Input

3 2 2
2 0 0
1 3
2 4
3 5

Output

5

Input

3 2 3
2 1 2
1 3
2 4
3 5

Output

0

Note

In the first sample case, coloring the trees with colors 2, 1, 1 minimizes the amount of paint used, which equals to 2 + 3 + 5 = 10. Note that 1, 1, 1 would not be valid because the beauty of such coloring equals to 1 ({1, 1, 1} is a way to group the trees into a single group of the same color).

In the second sample case, all the trees are colored, but the beauty of the coloring is 3, so there is no valid coloring, and the answer is  - 1.

In the last sample case, all the trees are colored and the beauty of the coloring matches k, so no paint is used and the answer is 0.


Solution

状态很好想, $dp[i][j][k]$表示将前$i$棵树涂成$j$个颜色段, 第$i$棵树的颜色为$k$的最小花费.
注意: 当$c_i e 0$时只有$dp[i][j][c_i]$才是合法的状态.
状态转移方程是
$$
dp[i][j][k]=
egin{cases}
min{dp[i-1][j][c_i], dp[i-1][j-1][k' e c_i}, & ext{if $c_i e 0$ and $k=c_i$;}
min{dp[i-1][j][k], dp[i-1][j-1][k' e k]}+cost[i][k], & ext{$c_i=0$;}
infty, & ext{otherwise.}
end{cases}
$$
初始化:
$dp[0][0][0]=0$

复杂度是$O(nkm^2)$, 尽管很高但还是可以过的 (早有人说CF机子快).
这个DP是可以优化到$O(nkm)$的.
我们在计算dp值的同时维护两个表

  • $m_1[i][j]: dp[i][j][0..m]$中的最小值
  • $m_2[i][j]: dp[i][j][0..m]$中的次小值

这样, 在上述dp转移方程中需要枚举$k'$的地方我们就可以利用这两个表避免枚举. 之所以要同时维护最大值和次大值是因为转移方程中的两式分别要求$k' e c_i$和$k' e k$, 为了保证我们不取到不合法的$k'$值, 若当$k'$取那个不合法的值时恰好取到最小值, 我们就要用次小值来转移.
初始化:
$dp[0][0][0]=0$
$m_1[0][0]=0$
其他值全部置成infty

Implementation

DP的写法一般有两种. 一种是

要计算$dp[i][j][k]$ (这里只是以本题为例, 并非所有dp状态都形如$dp[i][j][k]$) 时, 直接按dp转移方程, 用已经算出的dp值计算.

另一种是

从初始条件出发, 对于每个合法的且已经算出的dp状态, 我们用它来更新所有它能转移到的状态的答案.

这两种方式中, 前一种可概括为向前寻找, 后一种可概括为向后更新.
$O(nkm^2)$, 向后更新

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;

const int N{1<<7}, M(1e9+7);
LL dp[N][N][N];
int c[N];
LL cost[N][N];

void upd(LL &x, LL y){
	if(x==-1) x=y;
	else x=min(x, y);
}

int main(){
	int n, m, k;
	cin>>n>>m>>k;
	memset(dp, -1, sizeof(dp));
	for(int i=1; i<=n; i++) cin>>c[i];

	for(int i=1; i<=n; i++)
		for(int j=1; j<=m; j++) cin>>cost[i][j];

	dp[0][0][0]=0;

	for(int i=0; i<n; i++)
		for(int j=0; j<=k; j++)

			for(int k=0; k<=m; k++){
				if(~dp[i][j][k]){
					if(c[i+1]){
						if(k==c[i+1]) upd(dp[i+1][j][c[i+1]], dp[i][j][k]);
						else upd(dp[i+1][j+1][c[i+1]], dp[i][j][k]);
					}
					else{
						for(int x=1; x<=m; x++)
							if(x==k) upd(dp[i+1][j][x], dp[i][j][k]+cost[i+1][x]);
							else upd(dp[i+1][j+1][x], dp[i][j][k]+cost[i+1][x]);
					} 
				}
			}

	LL res=LLONG_MAX;
	for(int i=1; i<=m; i++)
		if(~dp[n][k][i]) res=min(res, dp[n][k][i]);

	cout<<(res==LLONG_MAX?-1LL:res)<<endl;
}

$O(nmk)$, 向前寻找

#include <bits/stdc++.h>
using namespace std;
using LL=long long;

const int N{1<<7};

LL dp[N][N][N], m1[N][N], m2[N][N];
int cost[N][N], col[N];

void upd(LL &x, LL y){
    if(x==-1) x=y;
    else x=min(x, y);
}

void solve(int n, int k, int m){
    memset(dp, -1, sizeof(dp));
    memset(m1, -1, sizeof(m1));
    memset(m2, -1, sizeof(m2));

    dp[0][0][0]=0;
    m1[0][0]=0;
    // m2[0][0]=-1;

    for(int i=1; i<=n; i++){
        for(int j=1; j<=k; j++)
            if(col[i]){
                auto &cur=dp[i][j][col[i]];

                if(dp[i-1][j][col[i]]!=-1)
                    upd(cur, dp[i-1][j][col[i]]);
                if(m1[i-1][j-1]!=-1 && dp[i-1][j-1][col[i]]!=m1[i-1][j-1])
                    upd(cur, m1[i-1][j-1]);
                else if(m2[i-1][j-1]!=-1)
                    upd(cur, m2[i-1][j-1]);
                if(cur!=-1){
                    if(m1[i][j]==-1 || m1[i][j]>cur){
                        upd(m2[i][j], m1[i][j]);
                        upd(m1[i][j], cur);
                    }
                    else{
                        upd(m2[i][j], cur);
                    }
                }
            }

            else{
                for(int c=1; c<=m; c++){
                    auto &cur=dp[i][j][c];
                    if(dp[i-1][j][c]!=-1){
                        upd(cur, dp[i-1][j][c]+cost[i][c]);
                    }
                    if(m1[i-1][j-1]!=-1 && m1[i-1][j-1]!=dp[i-1][j-1][c])
                        upd(cur, m1[i-1][j-1]+cost[i][c]);
                    else if(m2[i-1][j-1]!=-1)
                        upd(cur, m2[i-1][j-1]+cost[i][c]);
                    if(cur!=-1){
                        if(m1[i][j]==-1 || m1[i][j]>cur){
                            upd(m2[i][j], m1[i][j]);
                            upd(m1[i][j], cur);
                        }
                        else{
                            upd(m2[i][j], cur);
                        }
                    }
                }
            }
    }
    cout<<m1[n][k]<<endl;
}


int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n, m, k;
    cin>>n>>m>>k;
    for(int i=1; i<=n; i++)
        cin>>col[i];
    for(int i=1; i<=n; i++)
        for(int j=1; j<=m; j++)
            cin>>cost[i][j];
    solve(n, k, m);
    return 0;
}

P.S. 第一次用Markdown写博客, 感觉很不错.
Github Guides Mastering Markdown

原文地址:https://www.cnblogs.com/Patt/p/5838945.html