2024 CSP暑期集训营地 -线性DP&背包DP -晚测
-测评题单
T1 - 11845 快递物流
#include <bits/stdc++.h>
using namespace std;
const int N = 3510, M = 12810;
int f[M], v[N], w[N];
int n, m;
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
cin >> v[i] >> w[i]; // 体积与重量
// 01 背包模板
for (int i = 1; i <= n; i++)
for (int j = m; j >= v[i]; j--)
f[j] = max(f[j], f[j - v[i]] + w[i]);
cout << f[m] << endl;
system("pause");
return 0;
}
T2 - 1376 摆花
#include <bits/stdc++.h>
using namespace std;
const int mod = 1e6 + 7;
const int N = 110, M = 1010;
int n, m;
int a[N], f[M]; // f[i][j]:前 i 种花(所有的花盆数)摆放 j 盆时的方案数量
// 计数类 DP
int main()
{
cin >> n >> m; // 花种类,摆放共 m 盆
for (int i = 1; i <= n; i++)
cin >> a[i];
// 初始化摆放 0 盆花有一种方案数量
f[0] = 1;
for (int i = 1; i <= n; i++) // 枚举花的种类
for (int j = m; j >= 0; j--) // 枚举需要摆放的花盆数
for (int k = 1; k <= min(j, a[i]); k++) // 枚举当前花种类的摆放盆数
f[j] = (f[j] + f[j - k]) % mod;
cout << f[m] << endl;
system("pause");
return 0;
}
T3 - 1804 购买奖品
#include <bits/stdc++.h>
using namespace std;
const int N = 5100, M = 6000;
int n, m;
int w[N], v[N], f[M], len;
int main()
{
cin >> n >> m;
for (int i = 1, a, b, c; i <= n; i++)
{
cin >> a >> b >> c;
for (int j = 1; j <= c; j++) // 拆分成 c 独立物品
{
v[++len] = a, w[len] = b; // v 价格、w 价值
}
}
for (int i = 1; i <= len; i++)
{
for (int j = m; j >= 0; j--)
{
if (j >= v[i])
{
f[j] = max(f[j], f[j - v[i]] + w[i]);
}
}
}
cout << f[m] << endl;
system("pause");
return 0;
}
T4 - 1820 最便宜的通行费用
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int a[N][N], f[N][N];
int n;
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
cin >> a[i][j];
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
f[i][j] = 0x3f3f3f3f;
// 初始化
f[0][1] = 0;
// 枚举行
for (int i = 1; i <= n; i++)
{
// 枚举列
for (int j = 1; j <= n; j++)
{
f[i][j] = min(f[i - 1][j], f[i][j - 1]) + a[i][j];
}
}
cout << f[n][n] << endl;
system("pause");
return 0;
}
T5 - 1816 景点观光
#include <bits/stdc++.h>
using namespace std;
const int N = 1100;
int f1[N], f2[N], a[N];
int n, m;
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i], f1[i] = 1, f2[i] = 1;
// 两遍 LIS,求最长上升子序列和最长下降子序列长度
for (int i = 2; i <= n; i++)
for (int j = 1; j < i; j++)
if (a[i] > a[j])
f1[i] = max(f1[i], f1[j] + 1);
for (int i = n - 1; i >= 1; i--)
for (int j = n; j > i; j--)
if (a[i] > a[j])
f2[i] = max(f2[i], f2[j] + 1);
int ans = 0;
for (int i = 1; i <= n; i++) // 枚举分割点
ans = max(ans, f1[i] + f2[i] - 1); // 减去重复贡献
cout << ans << endl;
system("pause");
return 0;
}