问题描述
小C开了一家水果店,某天接到了一个大订单,要求将n个编号为1到n的水果打包成多个果篮,每个果篮的最大容量为m个水果,并且果篮中水果的编号必须连续。每个果篮的成本与容纳的水果数量及水果的体积相关,成本公式为:
k×⌊(u+v)/2⌋+sk×⌊(u+v)/2⌋+s
其中,uu是果篮中水果的最大体积,vv是果篮中水果的最小体积,kk是果篮中水果的数量,ss是一个常数,⌊x⌋⌊x⌋ 表示对xx进行下取整。
你的任务是帮助小C将这些水果打包成若干果篮,使得总成本最小。
例如:当有6个水果,体积为[1, 4, 5, 1, 4, 1]
,一个果篮最多装4个水果,常数ss为3时,最优的打包方案是将前三个水果(1, 4, 5)装成一个果篮,后三个水果(1, 4, 1)装成另一个果篮,最小的总成本为21。
测试样例
样例1:
输入:
n = 6, m = 4, s = 3, a = [1, 4, 5, 1, 4, 1]
输出:21
样例2:
输入:
n = 5, m = 3, s = 2, a = [2, 3, 1, 4, 6]
输出:17
样例3:
输入:
n = 7, m = 4, s = 5, a = [3, 6, 2, 7, 1, 4, 5]
输出:35
题解:
一开始想用DFS之类的暴力方法,因为你能做的操作是固定的,放一个,两个,三个,到m个进果篮,但是这样一定会超时,直接否定。
所以应该是使用动态规划,选定了是一维DP,发现当你在选择第X位水果时,当m=4,你可以与前4个水果组成果篮,3个,2个,或者是自己单独一个果篮,这时,动态规划就成了。
动态规划:DP[i]代表前i个水果成本最小值。
状态转移:
其中col计算了从x到y的果篮成本。
代码:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<queue>
#include<stack>
#include<vector>
#include<unordered_set>
#include<unordered_map>
#include<map>
#include<set>
using namespace std;
typedef long long int ll;
int col(int x,int y,vector<int> a,int s){
int maxnum=0,minnum=100000;
for(int i=x;i<=y;i++){
if(a[i-1]>maxnum){
maxnum=a[i-1];
}
if(a[i-1]<minnum){
minnum=a[i-1];
}
}
return (y-x+1)*((minnum+maxnum)/2)+s;
}
int pro(int x,int y,vector<int> dp,vector<int> a,int s,int m){
int t1=col(x,y,a,s)+dp[x-1];
int t2=dp[y];
//cout << "x: " << x << " y: " << y << " t1: " << t1 << " t2: " << t2 << "\n";
return min(t1,t2);
}
int solution(int n, int m, int s, vector<int> a) {
vector<int> dp(n+2,0);
for(int i=1;i<=n;i++){
dp[i]=dp[i-1]+a[i-1]+s;
if(i<=m){
for(int j=1;j<i;j++){
dp[i]=pro(j,i,dp,a,s,m);
}
}
else{
for(int j=i-m+1;j<i;j++){
dp[i]=pro(j,i,dp,a,s,m);
}
}
/*
for(int j=0;j<=n;j++){
cout << dp[j] << " ";
}
cout << "\n";
*/
}
//cout << dp[n] << "\n";
return dp[n];
}
int main() {
cout << (solution(6, 4, 3, {1, 4, 5, 1, 4, 1}) == 21) << endl;
cout << (solution(5, 3, 2, {2, 3, 1, 4, 6}) == 17) << endl;
cout << (solution(7, 4, 5, {3, 6, 2, 7, 1, 4, 5}) == 35) << endl;
return 0;
}