题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1158
题目描述:
Description
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
题目大意:
输入第一行一个整数n,代表n个月,接下来一行输入三个整数a,b,c分别是a代表雇佣一个工人的钱,b代表工人每个月的工资,c代表辞退一个工人的钱,接下来一行是n个整数,代表每个月所需要的最少的工人数目,叫你求出完成这项工程所需要花费的最少数量的钱
题目分析:
二维数组dp[i][j]代表第i个月雇佣j个工人所需要花费的最少的钱,处理第i个月的时候先来看前面一个月.
状态转移方程:
if(j>num[i-1])//这个月的规定人数比前一个月的规定人数要多,那么招聘了人
dp[i][j]=dp[i-1][num[i-1]]+j*b+(j-num[i-1])*a;
else//这个月的规定人数比前一个月的规定人数要少,那么解雇人
dp[i][j]=dp[i-1][num[i-1]]+j*b+(num[i-1]-j)*c;
if(k>j)//前面一个月的实际人数比这个月多,需要解雇
dp[i][j]=min(dp[i][j],dp[i-1][k]+j*b+(k-j)*c);
else//前面一个月的实际人数比这个月少,需要招聘
dp[i][j]=min(dp[i][j],dp[i-1][k]+j*b+(j-k)*a);
Ac代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
int dp[13][1005];//dp[i][j]代表第i个月雇佣j个工人所需要花费的最少的钱
int num[13];
int a,b,c;//a代表雇佣一个工人的钱,b代表工人每个月的工资,c代表辞退一个工人的钱
int n,m,ans;//一共n个月,m代表最多需要的工人数目是m,ans代表最终需要的最少钱数
int main()
{
while(1)
{
cin>>n;
if(n==0)
break;
m=0;
memset(dp,0,sizeof(dp));
cin>>a>>b>>c;
for(int i=1;i<=n;i++)
{
cin>>num[i];
m=max(num[i],m);
}
for(int i=0;i<=m;i++)
dp[0][i]=i*(a+b);//第0个月雇佣i个工人的钱
for(int i=1;i<=n;i++)
{
for(int j=num[i];j<=m;j++)//这个月最少需要的人数是num[i],最多只需要雇佣m个工人
{
if(j>num[i-1])//这个月的规定人数比前一个月的规定人数要多,那么招聘了人
dp[i][j]=dp[i-1][num[i-1]]+j*b+(j-num[i-1])*a;
else//这个月的规定人数比前一个月的规定人数要少,那么解雇人
dp[i][j]=dp[i-1][num[i-1]]+j*b+(num[i-1]-j)*c;
for(int k=num[i-1];k<=m;k++)//还是针对前面一个月,因为前面一个月的人数不一定是num[i-1]个
{
if(k>j)//前面一个月的实际人数比这个月多,需要解雇
dp[i][j]=min(dp[i][j],dp[i-1][k]+j*b+(k-j)*c);
else//前面一个月的实际人数比这个月少,需要招聘
dp[i][j]=min(dp[i][j],dp[i-1][k]+j*b+(j-k)*a);
}
}
}
ans=0xfffffff;
for(int i=num[n];i<=m;i++)
ans=min(ans,dp[n][i]);
cout<<ans<<endl;
}
return 0;
}