题目:
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
0
Sample Output
199
翻译:
首行出入月份;
次行输入三个值表示雇佣成本、每个人每个月的工资、和解雇成本。
第三行出入每一个月份需要几个人。
思路:
这个题首先会想到如果用以为dp数组的话肯定是表示第i个月需要的最小支出。但是如果单单用一位数组的话会感觉做不出来。那么我们就要考虑二维数组,其实说实话这个状态还是蛮难找的,------》二维dp数组表示第 i 个月所雇佣的 j 人数,那么我们可以通过求第i个月的最小成本最终递推到第n个月的成本。
状态方程:
if(j>=k)
dp[i][j]=min(dp[i][j],dp[i-1][k]+(j-k)a+jb);
else
dp[i][j]=min(dp[i][j],dp[i-1][k]+(k-j)c+jb);
这个状态方程还是不好找。表示上一个月的花费与这个月的作比较寻找最小的
代码:
#include<iostream>
#include<algorithm>
#include<math.h>
#include<stdio.h>
#include<cstring>
#include <queue>
#include<iomanip>
#include<string>
#include<map>
#define inf 0x3f3f3f3f
using namespace std;
int arr[20],dp[20][2200];
int main()
{
int n;
while(cin>>n)
{
if(n==0)
break;
int a,b,c,m=0;
memset(dp,inf,sizeof(dp));
cin>>a>>b>>c;
for(int i=1;i<=n;i++)
{
cin>>arr[i];
m=max(m,arr[i]);
}
for(int i=arr[1];i<=m;i++)
dp[1][i]=(a+b)*i;
for(int i=2;i<=n;i++)
{
for(int j=arr[i];j<=m;j++)
{
for(int k=arr[i-1];k<=m;k++)
{
if(j>=k)
dp[i][j]=min(dp[i][j],dp[i-1][k]+(j-k)*a+j*b);
else
dp[i][j]=min(dp[i][j],dp[i-1][k]+(k-j)*c+j*b);
}
}
}
int g=inf;
for(int i=1;i<=m;i++)
g=min(g,dp[n][i]);
cout<<g<<endl;
}
}