题解:P1541 [NOIP 2010 提高组] 乌龟棋
提供一个不一样的转移思路。
线性 DP 的思路很好想,直接设状态
很明显空间炸了。首先发现
然后考虑转移,首先从小到大枚举卡片数总
但是应优先转移使用卡片
至于使用卡片
转移方程如下:
注意滚动数组的转移顺序应是从后往前,以避免覆盖未处理的状态,影响正确性。
全代码
#include<bits/stdc++.h>
#define int long long
#define I_love_Foccarus return
#define cin_fast ios::sync_with_stdio(false) , cin.tie(0) , cout.tie(0)
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define deap(i,a,b) for(int i=a;i>=b;i--)
#define endl '\n'
//#define getchar getc
#define pii pair<int,int>
#define mk(a,b) make_pair(a,b)
#define fi first
#define se second
#define pd(a) push_back(a)
#define inui(a) a = read_unsigned_int()
#define in(a) a = read_int()
#define inp(a , b) a = read_int() , b = read_int()
#define inl(a) a = read_long_long()
using namespace std;
const int Size = 1 << 14;
const int N = 4e2 + 5 , M = 1e2 + 2e1 + 5;
const int inf = 0x3f3f3f3f;
inline char getc() {
static char syn[Size] , *begin = syn , *end = syn;
if(begin == end) begin = syn , end = syn + fread(syn , 1 , Size , stdin);
I_love_Foccarus *begin ++;
}
inline int read_unsigned_int() {
int x = 0;
char ch = getchar();
while('9' < ch || ch < '0') ch = getchar();
while('0' <= ch && ch <= '9') x = (x << 3) + (x << 1) + ch - '0' , ch = getchar();
I_love_Foccarus x;
}
inline int read_int() {
int x = 0;
char ch = getchar();
bool f = 0;
while('9' < ch || ch < '0') f |= ch == '-' , ch = getchar();
while('0' <= ch && ch <= '9') x = (x << 3) + (x << 1) + ch - '0' , ch = getchar();
I_love_Foccarus f ? -x : x;
}
inline int read_long_long() {
long long x = 0;
char ch = getchar();
bool f = 0;
while('9' < ch || ch < '0') f |= ch == '-' , ch = getchar();
while('0' <= ch && ch <= '9') x = (x << 3) + (x << 1) + ch - '0' , ch = getchar();
I_love_Foccarus f ? -x : x;
}
int n , m , w[N] , dp[M][M][M] , t[5];
signed main() {
//cin_fast;
in(n) , in(m);
for(int i = 1 ; i <= n ; i ++) in(w[i]);
for(int i = 1 ; i <= m ; i ++) {
int x;
in(x);
t[x] ++;
}
dp[0][0][0] = w[1];
for(int i = 1 ; i <= m ; i ++) {
for(int a = t[1] ; a >= 0 ; a --) {
for(int b = t[2] ; b >= 0 ; b --) {
for(int c = t[3] ; c >= 0 ; c --) {
if(a + b + c <= i) {
int d = i - a - b - c;
if(d > t[4]) continue;
int j = 1 + a + 2 * b + 3 * c + 4 * d;
if(d) dp[a][b][c] += w[j];
if(a) dp[a][b][c] = max(dp[a][b][c] , dp[a - 1][b][c] + w[j]);
if(b) dp[a][b][c] = max(dp[a][b][c] , dp[a][b - 1][c] + w[j]);
if(c) dp[a][b][c] = max(dp[a][b][c] , dp[a][b][c - 1] + w[j]);
}
}
}
}
}
cout<<dp[t[1]][t[2]][t[3]];
I_love_Foccarus 0;
}