问题描述:
A project manager wants to determine the number of the workers needed in every month. He does know the minimal number of the workers needed in each month. When he hires or fires a worker, there will be some extra cost. Once a worker is hired, he will get the salary even if he is not working. The manager knows the costs of hiring a worker, firing a worker, and the salary of a worker. Then the manager will confront such a problem: how many workers he will hire or fire each month in order to keep the lowest total cost of the project.
Input
The input may contain several data sets. Each data set contains three lines. First line contains the months of the project planed to use which is no more than 12. The second line contains the cost of hiring a worker, the amount of the salary, the cost of firing a worker. The third line contains several numbers, which represent the minimal number of the workers needed each month. The input is terminated by line containing a single '0'.
Output
The output contains one line. The minimal total cost of the project.
Sample Input
3 4 5 6 10 9 11 0Sample Output
199题目题意:我们有俩种操作,可以雇佣人和开除人,每种操作都有一定的花费,每个月还得给在职的员工发工资,每个月有一个最小员工数(不能低于它),问n个月的最小花费
题目分析:很明显的dp[i]保存第i个月的最小花费,但是这样显然不够,因为你无法转移到下一个状态,还有一个关键的元素是人数.
知道这个月的人数和dp[i]转移到下一个月的人数和dp[i+1]非常好写了,少人就加多人就减。
每个人的人数是从最小员工数到(题目出现的最小员工数)超过它就是浪费钱了
代码如下:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<vector>
using namespace std;
const int maxn=15;
struct note
{
int cost,num;
};
struct note dp[maxn][200];
int a[maxn],Num[maxn];//保存每个月中,人数有多少种
int main()
{
int n;
while (scanf("%d",&n)!=EOF) {
if (n==0) break;
int p,q,r,Max=0;
scanf("%d%d%d",&p,&q,&r);
for (int i=1;i<=n;i++) {
scanf("%d",&a[i]);
Max=max(Max,a[i]);
}
memset (Num,0,sizeof (Num));
for (int i=1;i<=n;i++) {
for (int j=a[i];j<=Max;j++) {
if (i==1) {
struct note sum;
sum.cost=j*p+j*q;
sum.num=j;
dp[i][Num[i]++]=sum;
}
else {
int ans=0x3f3f3f3f;
struct note sum;
sum.num=j;
for (int k=0;k<Num[i-1];k++) {
int s1;
if (dp[i-1][k].num>=j) {
s1=(dp[i-1][k].num-j)*r;
}
else {
s1=(j-dp[i-1][k].num)*p;
}
s1+=j*q;
s1+=dp[i-1][k].cost;
ans=min(ans,s1);//找到最小的那个花费
}
sum.cost=ans;
dp[i][Num[i]++]=sum;
}
}
}
int ans=0x3f3f3f3f;
for (int i=0;i<Num[n];i++) ans=min(ans,dp[n][i].cost);
printf("%d\n",ans);
}
return 0;
}