Several common types of DP.

Several common types of DP.

1. The path DP.

Examples 1.P1216 [USACO1.5] [IOI1994] Digital triangular Number
Title portal

The title of each selected path only two points, well written dp, see detailed explanation below code.

#include<bits/stdc++.h>
using namespace std;
const int N=1e3+5; 
int n,dp[N][N],a[N][N];//状态的确立:dp[i][j]表示终点为第i行第j列的最大值 
int main(){
	cin>>n;
	for(int i=1;i<=n;i++)
		for(int j=1;j<=i;j++)
		{
			cin>>a[i][j];
			if(i==n) //确立初始状态:即最后一行的状态. 
			dp[i][j]=a[i][j]; 
	**加粗样式**	}
	for(int i=n-1;i>=1;i--)//从下往上递推 
		for(int j=1;j<=i;j++)
			dp[i][j]=max(dp[i+1][j]+a[i][j],dp[i+1][j+1]+a[i][j]);//每个点只能从由下一行的左边一个点或者右边一个点走到 
	cout<<dp[1][1]<<endl;//反过来想:起点为(1,1)的最大路径 倒过来走终点必为 (1,1) 
	return 0;
} 

Simple recursive DP.

P2837 [USACO08FEB]Dining Cows B

Suppose DP [i] i is the minimum number of cows before modification.
Of the i-cow for discussion. If the first cow 2 i do not control: dp [i] = dp [ i -1], if the i-1 and the cow is divided into two cases: 1. if not modified, dp [i] is equal to the front 2 number, 2. If you want to modify, is then equal to dp [i-1] +1, cnt can be one-dimensional, because dp [i] is obtained from the previous state, so the space can be compressed to O (1). See the following code.

#include<bits/stdc++.h>
using namespace std;
int ans,cnt,n,x;
int main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>x;
		x==2?cnt++:ans=min(ans+1,cnt);
	}
	cout<<ans<<endl;
	return 0;
}

State type dp

P1877 [HAOI2012] volume control

Set DP [i] [j] of the j i song volume can reach,
DP [i] [j] =. 1 shows this state to reach 0 otherwise can not be reached, and finally again to a crude descending sweep.

#include<bits/stdc++.h>
using namespace std;
int dp[1005][1005],a[55];
int main(){
	int n,st,mx;
	cin>>n>>st>>mx;
	for(int i=1;i<=n;i++) cin>>a[i];
	dp[0][st]=1; 
	for(int i=1;i<=n;i++)
		for(int j=0;j<=mx;j++)
		{
			if(dp[i-1][j]&&a[i]+j<=mx) dp[i][a[i]+j]=1;
			if(dp[i-1][j]&&j-a[i]>=0) dp[i][j-a[i]]=1;
		}
	for(int i=mx;i>=0;i--)
		if(dp[n][i])
		{
			printf("%d\n",i);
			return 0;
		}
	puts("-1");
	return 0; 
}
Published 18 original articles · won praise 14 · views 356

Guess you like

Origin blog.csdn.net/weixin_45750972/article/details/105056000