# 2023.2.6 普及组 day2

Yapink 2023-02-06 16:02:12
• 第一题：简单的01背包问题，可优化一维

#include <iostream>

using namespace std;

const int N =  1010;

int n, m;
int f[N];

int main()
{
cin >> m >> n;
for (int i = 1; i <= n; i ++ )
{
int v, w;
cin >> v >> w;
for (int j = m; j >= v; j -- )
f[j] = max(f[j], f[j - v] + w);
}

cout << f[m] << endl;
return 0;
}
• 第二题：简单的完全背包模型，需要注意记得开longlong，不然爆int。

#include <iostream>

using namespace std;

typedef long long LL;

const int N = 10000010;

int n, m;
LL f[N];

int main()
{
scanf("%d%d", &m, &n);
for (int i = 1; i <= n; i ++ )
{
int v, w;
scanf("%d%d", &v, &w);
for (int j = v; j <= m; j ++ )
f[j] = max(f[j], f[j - v] + w);
}

printf("%lld\n", f[m]);
return 0;
}

第三题：dp，考虑从两个方向过来的方案，列出状态转移方程。

#include <iostream>

using namespace std;

const int N = 110;

int n, m;
int w[N][N];
int f[N][N];

int main()
{
int T;
cin >> T;
while (T -- )
{
cin >> n >> m;
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= m; j ++ )
cin >> w[i][j];

for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= m; j ++ )
f[i][j] = max(f[i - 1][j], f[i][j - 1]) + w[i][j];

cout << f[n][m] << endl;
}

return 0;
}

#include <iostream>

using namespace std;

const int N = 110, mod = 1e6 + 7;

int n, m;
int a[N];
int f[N][N];

int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++ ) cin >> a[i];

f[0][0] = 1;
for (int i = 1; i <= n; i ++ )
for (int j = 0; j <= m; j ++ )
for (int k = 0; k <= a[i]; k ++ )
if (j >= k)
f[i][j] = (f[i][j] + f[i - 1][j - k]) % mod;

cout << f[n][m] << endl;
return 0;
}

...全文
11 回复 打赏 收藏 转发到动态 举报

49,440

• 近7日
• 近30日
• 至今

刷题！