东方博宜OJ 6218:条形蛋糕 ← 完全背包

​【题目来源】
https://oj.czos.cn/p/6218

【题目描述】
有一条长度为 n 的条形蛋糕。已知长度为 i 的蛋糕可以卖出价格 pi。你可以把蛋糕切成若干段,每段长度为正整数,切割次数不限。请问这条长度为 n 的蛋糕最多能卖多少钱。

【输入格式】
第一行一个整数 n。
第二行 n 个正整数 p1,P2,…,Pn,表示不同长度蛋糕的价格。​​​​​​​

【输出格式】
输出一个整数,表示最大总价格。​​​​​​​

【输入样例】
10
1 5 8 9 10 17 17 20 24 30

【输出样例】
30

【数据范围】
1≤n≤10^3,1≤pi≤10^5

【算法分析】
● 完全背包问题(https://blog.csdn.net/hnjzsyjyj/article/details/126126183)的一维优化代码。

#include<bits/stdc++.h>
using namespace std;

const int maxn=1e3+5;
int f[maxn];

int main() {
    int n,V;
    cin>>n>>V;
    for(int i=1; i<=n; i++) {
        int vol,val;
        cin>>vol>>val;
        for(int j=vol; j<=V; j++)
            f[j]=max(f[j],f[j-vol]+val);
    }
    cout<<f[V]<<endl;
    return 0;
}

/*
in:
4 5
1 2
2 4
3 4
4 5

out:
10
*/

【算法代码】

#include<bits/stdc++.h>
using namespace std;

const int N=1e4+5;
int dp[N];

int main() {
    int n,val;
    cin>>n;
    for(int i=1; i<=n; i++) {
        cin>>val;
        for(int j=i; j<=n; j++) {
            dp[j]=max(dp[j],dp[j-i]+val);
        }
    }
    cout<<dp[n]<<endl;
    return 0;
}

/*
in:
10
1 5 8 9 10 17 17 20 24 30

out:
30
*/



【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/126126183
https://blog.csdn.net/hnjzsyjyj/article/details/159050238


 

​

posted @ 2026-10-23 06:25  Triwa  阅读(14)  评论(0)    收藏  举报