0
点赞
收藏
分享

微信扫一扫

P1842. 牛奶桶

三维控件研究 2022-04-13 阅读 21
算法c++

题目链接:

题目描述:

题目分析:

  • 思路:求 n个小桶和m个中桶凑出的体积最接近 M
  • 答案:求出最接近 M 的那个体积

第一种:枚举

分析:

可以直接枚举小桶的个数,进而确定中桶能选择的个数,求出能组成的体积数

代码:

/*
 * 暴力枚举 每次选择的小桶的个数(0 ~ [m/x]向下取整)和中桶的个数(剩余体积(m - 小桶的个数 * x) / y)的最大体积
 * 时间复杂度O(m)
 */
#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
typedef long long LL;
typedef pair<int, int> PII;
const int N = 1e3 + 10;

int main()
{
    int x, y, m;
    cin >> x >> y >> m;
    int res = 0;
    for(int i = 0; i <= m / x; i++)
    {
        res = max(res, i * x + (m - i * x) / y * y);
    }
    cout << res << endl;
    return 0;
}

第二种:dp

分析:

可以把两种桶当作两个物品,体积和价值都是输入的值,然后进行完全背包的求解就可以了

代码:

/*
 * 转换为完全背包来做, 每一个体积都对应这个小桶这一次选或者不选 dp[i]: 体积为i时的最大的价值是多少
 * 状态转移方程: dp[i] = max(dp[i], dp[i - w] + v);(w是体积,v是价值)
 * 时间复杂度O(m)
 */
#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
typedef long long LL;
typedef pair<int, int> PII;
const int N = 1e3 + 10;
int dp[N];
int w[2], v[2];

int main()
{
    int m;
    for(int i = 0; i < 2; i++) cin >> v[i], w[i] = v[i];
    cin >> m;
    for(int i = 0; i < 2; i++)
    {
        for(int j = w[i]; j <= m; j++)
        {
        	// 状态转移
            dp[j] = max(dp[j], dp[j - w[i]] + v[i]);
        }
    }
    cout << dp[m] << endl;
    return 0;
}

第三种: bfs(大怨种,不建议学习)

分析:

可以枚举可能生产的 (n,m) 的数对,然后算出每个数对能凑出的体积,选择最大且合理的那个就是最终总答案。

代码:

/*
 * 使用 bfs 遍历 x 和 y 的个数,然后使用st数组标记是否出现过,不然会每一组数会出现无数次,会卡死的
 * 时间复杂度为 O(m*m)
 */
#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
typedef long long LL;
typedef pair<int, int> PII;
const int N = 1e3 + 10;
// 记录数对是否出现过
bool st[N][N];

int main()
{
    int x, y, m;
    cin >> x >> y >> m;
    queue<PII> q;
    // 最开始只有数对(0,0)
    q.push({0, 0});
    int res = 0;
    while(!q.empty())
    {
        auto t = q.front();
        q.pop();
        // 算出当前这个数对能凑的体积
        int ans = t.x * x + t.y * y;
        // 合理且没有被算过,那么才能被算且加入队列
        if(ans <= m && !st[t.x][t.y])
        {
            res = max(res, ans);
            if(!st[t.x + 1][t.y])   q.push({t.x + 1, t.y});
            if(!st[t.x][t.y + 1])   q.push({t.x, t.y + 1});
        }
        // 标记这个数对已经被算过
        st[t.x][t.y] = true;
    }
    cout << res << endl;
    return 0;
}

今天居然能写出 bfs这种算法,我是没想到我居然做得出来这种事。

举报

相关推荐

0 条评论