magic balls
http://acm.hdu.edu.cn/showproblem.php?pid=5125
分析
代码
按长度 — 值优先
// hdu 5125 magic balls
#include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
#define MXN 1010
int a[MXN], b[MXN];
// dp[i][j]:消耗能量不超过i、长度为j的序列的最小尾元素值
// len[i]:消耗能量不超过i的最长序列长度
int dp[MXN][MXN], len[MXN], N, M, ans;
int main() {
int T, pos;
scanf("%d", &T);
while (T--) {
scanf("%d%d", &N, &M);
for(int i = 1; i <= N; ++i) scanf("%d%d", a+i, b+i);
memset(len, 0, sizeof len);
memset(dp, INF, sizeof dp);
for(int i = 0; i <= M; ++i) dp[i][0] = 0;
for(int i = 1; i <= N; ++i){
for(int j = M; j >= 0; --j){
// a数组的元素,不改变能量消耗
if(dp[j][len[j]] < a[i]) dp[j][++len[j]] = a[i];
else *lower_bound(dp[j], dp[j]+len[j]+1, a[i]) = a[i];
// b数组的元素,使得能量消耗增1
if(j > 0){
pos = lower_bound(dp[j-1], dp[j-1]+len[j-1]+1, b[i]) - dp[j-1];
if(len[j] < pos){
for(int k = len[j]+1; k <= pos; ++k) dp[j][k] = b[i]; // 连续修改多个
len[j] = pos;
}
else dp[j][pos] = min(dp[j][pos], b[i]);
}
}
}
ans = max(len[0], len[1]);
for(int i = 2; i <= M; ++i) ans = max(ans, len[i]);
printf("%d\n", ans);
}
return 0;
}
按下标 — 长度优先
- 递推贪心策略,设a[i](或b[i])结尾的序列长度为len,能量消耗为m
- 当len1 > len2,m1 <= m2,显然,(len1,m1)比(len2,m2)更优;
- 当len1 > len2,m1 > m2,则(len1,m1)比(len2,m2)更优。为什么?难道是因为若(len2,m2)能发展出最优解,则通过(len1,m1)也必然能得到最优解?还是“递推有特殊规律”?
- 当len1 == len2,m1 < m2,显然,(len1,m1)比(len2,m2)更优;
// hdu 5125 magic balls
#include <bits/stdc++.h>
using namespace std;
#define MXN 10//10
int a[MXN], b[MXN];
// da[i]:以a[i]结尾的序列的最大长度
// db[i]:以b[i]结尾的序列的最大长度
// ma[i]:以a[i]结尾的序列的能量消耗值
// mb[i]:以b[i]结尾的序列的能量消耗值
// len[i]:消耗能量i的序列
int len[MXN], da[MXN], db[MXN], ma[MXN], mb[MXN], N, M, ans;
int main() {
int T, pos;
scanf("%d", &T);
while (T--) {
scanf("%d%d", &N, &M);
for(int i = 1; i <= N; ++i) scanf("%d%d", a+i, b+i);
memset(len, 0, sizeof len);
memset(da, 0, sizeof da);
memset(db, 0, sizeof db);
memset(ma, 0, sizeof ma);
memset(mb, 0, sizeof mb);
for(int i = 1; i <= N; ++i){
for(int j = 0; j < i; ++j){
if(a[i] > a[j] && (da[i] < da[j]+1 ||(da[i] == da[j]+1 && ma[i] > ma[j]))){
da[i] = da[j]+1;
ma[i] = ma[j];
len[ma[i]] = max(len[ma[i]], da[i]);
}
if(a[i] > b[j] && (da[i] < db[j]+1 ||(da[i] == db[j]+1 && ma[i] > mb[j]))){
da[i] = db[j]+1;
ma[i] = mb[j];
len[ma[i]] = max(len[ma[i]], da[i]);
}
if(b[i] > a[j] && (db[i] < da[j]+1 ||(db[i] == da[j]+1 && mb[i] > ma[j]+1))){
db[i] = da[j]+1;
mb[i] = ma[j]+1;
len[mb[i]] = max(len[mb[i]], db[i]);
}
if(b[i] > b[j] && (db[i] < db[j]+1 ||(db[i] == db[j]+1 && mb[i] > mb[j]+1))){
db[i] = db[j]+1;
mb[i] = mb[j]+1;
len[mb[i]] = max(len[mb[i]], db[i]);
}
}
}
ans = 0;
for(int i = 0; i <= M; ++i) ans = max(ans, len[i]);
printf("%d\n", ans);
}
return 0;
}