2018 USP-ICMC E. Loppinha, the boy who likes sopinha

Link:https://codeforces.com/gym/101875/problem/E

Solution:显然是一道动态规划题,状态也比较好想,dp[i][j][k]表示前i个用了j个转换,当前连续k个1 的最小消耗值

答案就是dp[n][?][?]中满足消耗值小于等于体力值的状态中j的最小值

转移就分为s[i] == '1' 和 s[i] == '0'了

s[i] == '1' : 

换:dp[t1][j][0] = qmin(dp[t1][j][0], dp[t2][j-1][k]);(j != 0)

不换:dp[t1][j][k] = qmin(dp[t1][j][k], dp[t2][j][k-1]) + k; (k != 0)

s[i] == '0':

dp[t1][j][0] = qmin(dp[t1][j][0], dp[t2][j][k]);

 

n是450的,n ^ 3大概是7e9,不会TLE但是会MLE

考虑到i状态只与i-1状态有关,所以可以开成滚动数组

AC Code:

template inline T qmin(T a, T b) { return a < b ? a : b; }

int dp[2][maxn][maxn];
char s[maxn];
int n, m;

int main()
{
	scanf("%d %d", &n, &m);
	scanf(" %s", s + 1);
	memset(dp, 0x3f, sizeof dp);
	dp[0][0][0] = 0;
	int t1 = 1, t2 = 0;
	rep(i, 1, n){
		if(t1){
			rep(j, 0, n) rep(k, 0, n) dp[1][j][k] = inf;
		} else {
			rep(j, 0, n) rep(k, 0, n) dp[0][j][k] = inf;
		}
		rep(j, 0, i){
			rep(k, 0, i){
				if(s[i] == '1'){
					if(k) dp[t1][j][k] = qmin(dp[t1][j][k], dp[t2][j][k-1]) + k;
					if(j) dp[t1][j][0] = qmin(dp[t1][j][0], dp[t2][j-1][k]);
				} else {
					dp[t1][j][0] = qmin(dp[t1][j][0], dp[t2][j][k]);
				}
			}
		}
		swap(t1, t2);
	}
	int ans = inf;
	rep(j, 0, n){
		rep(k, 0, n){
			if(dp[t2][j][k] <= m) ans = qmin(ans, j);
		}
	}
	printf("%d\n", ans);
	return 0;
}

over

你可能感兴趣的:(DP)