Employment Planning
Problem 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
题意:雇佣工人,给出需要雇佣的月数。和每个工人雇佣费,工资,及遣散费,求n个月总共的花费最少
题解:枚举DP
状态转移方程为dp[i][j]=min(dp[i-1][k]+安排+j*wage)(第i月时剩下j个工人的的花费)
当j>k时表明当前可用工人少,应在雇佣此时安排=(j-k)*hire
当k<j时表明当前的工人过多,应该遣散部分安排=(k-j)*fire
k的范围应该为(k>=a[i]&&k<max) a[i]表示第i月的工人数,max表示所有月份中最大的工人数
AC代码:
#include<iostream>
#include<stdio.h>
using namespace std;
int m[13][1005];
int b[13];
int mi(int a,int b)
{
return a<b?a:b;
}
int main()
{
int n,i,mx,hire,wage,dismiss,jk,k,j;
while(scanf("%d",&n)&&n)
{
mx=0;
scanf("%d%d%d",&hire,&wage,&dismiss);
for(i=1;i<=n;i++) scanf("%d",&b[i]);
for(i=1;i<=n;i++)
{
if(b[i]>mx) mx=b[i];
}
for(i=b[1];i<=mx;i++) m[1][i]=i*(hire+wage);
for(i=2;i<=n;i++)
{
for(j=b[i];j<=mx;j++)
{
jk=100000000;
for(k=b[i-1];k<=mx;k++)
{
if(k<j) jk=mi(jk,m[i-1][k]+(j-k)*hire+j*wage);
else jk=mi(jk,m[i-1][k]+(k-j)*dismiss+j*wage);
}
m[i][j]=jk;
}
}
jk=100000000;
for(i=b[n];i<=mx;i++)
{
if(m[n][i]<jk) jk=m[n][i];
}
printf("%d\n",jk);
}
return 0;
}
#include<stdio.h>
using namespace std;
int m[13][1005];
int b[13];
int mi(int a,int b)
{
return a<b?a:b;
}
int main()
{
int n,i,mx,hire,wage,dismiss,jk,k,j;
while(scanf("%d",&n)&&n)
{
mx=0;
scanf("%d%d%d",&hire,&wage,&dismiss);
for(i=1;i<=n;i++) scanf("%d",&b[i]);
for(i=1;i<=n;i++)
{
if(b[i]>mx) mx=b[i];
}
for(i=b[1];i<=mx;i++) m[1][i]=i*(hire+wage);
for(i=2;i<=n;i++)
{
for(j=b[i];j<=mx;j++)
{
jk=100000000;
for(k=b[i-1];k<=mx;k++)
{
if(k<j) jk=mi(jk,m[i-1][k]+(j-k)*hire+j*wage);
else jk=mi(jk,m[i-1][k]+(k-j)*dismiss+j*wage);
}
m[i][j]=jk;
}
}
jk=100000000;
for(i=b[n];i<=mx;i++)
{
if(m[n][i]<jk) jk=m[n][i];
}
printf("%d\n",jk);
}
return 0;
}
为了明天所以选择坚定的执着今天。