Description
Write a program to help John plan his fishing trip to maximize the number of fish expected to be caught. The number of minutes spent at each lake must be a multiple of 5.
Input
Output
If multiple plans exist, choose the one that spends as long as possible at lake 1, even if no fish are expected to be caught in some intervals. If there is still a tie, choose the one that spends as long as possible at lake 2, and so on. Insert a blank line between cases.
Sample Input
2 1 10 1 2 5 2 4 4 10 15 20 17 0 3 4 3 1 2 3 4 4 10 15 50 30 0 3 4 3 1 2 3 0
Sample Output
45, 5 Number of fish expected: 31 240, 0, 0, 0 Number of fish expected: 480 115, 10, 50, 35 Number of fish expected: 724
题意解释:
John现有h个小时的空闲时间,他打算去钓鱼。钓鱼的地方共有n个湖,所有的湖沿着一条单向路顺序排列(John每在一个湖钓完鱼后,他只能走到下一个湖继续钓),John必须从1号湖开始钓起,但是他可以在任何一个湖结束他此次钓鱼的行程。
此题以5分钟作为单位时间,John在每个湖中每5分钟钓的鱼数随时间的增长而线性递减。每个湖中头5分钟可以钓到的鱼数用fi表示,每个湖中相邻5分钟钓鱼数的减少量用di表示,John从任意一个湖走到它下一个湖的时间用ti表示。
求一种方案,使得John在有限的h小时中可以钓到尽可能多的鱼。
经典的贪心例题,采用枚举+贪心的解题思路,题目难度适中。
此题还可以用DP解答,但与贪心相比,过程较复杂。
思路:
首先须注意的一点是,John只能向前走,返回的话只会增加John在路上的时间,因而减少他钓鱼的时间。因此此题解题步骤如下:
1、 枚举John经过的最后一个湖,每种情况减去所需步行的时间,剩下的就是钓鱼的时间。
2、 每5分钟选取钓鱼量最多的湖进行钓鱼,直到时间耗尽。
3、 在所有枚举的情况中选择钓鱼量最多的情况,即为问题的最优解。
此题需要注意的几个问题:
1、 如果解不唯一,选择在第一个湖耗时最多的解;如果仍旧存在不惟一解,选择在第二个湖耗时最多的解,以此类推。
2、 随着时间的增加,在某个湖中的钓鱼数可能会出现负数,此时应将该湖中每个时间单位的钓鱼数更新为零。
3、 在测试数据或程序运行的过程中可能出现每个湖鱼数全为0的情况,注意特别处理。
4、 枚举时,结束的标志是剩余时间<=0。
#include<stdio.h>
#include<string.h>
int main()
{
int h,n,i,j,c=0,ht,ft[30],ans[30][30],f[30],t[30],d[30];
while(scanf("%d%d",&n,&h)&&n)
{
if(c!=0)
printf("\n");
c=1;
h*=12;//可用时间,一个小时有12个五分钟
memset(ans,0,sizeof(ans));
memset(f,0,sizeof(f));//最初钓鱼量
memset(t,0,sizeof(t));//表示到下一个湖的时间
memset(d,0,sizeof(d));//单位时间内的减少量
for(i=1; i<=n; i++)
scanf("%d",&f[i]);
for(i=1; i<=n; i++)
scanf("%d",&d[i]);
for(i=1; i<n; i++)
scanf("%d",&t[i]);
for(i=1; i<=n; i++)
{
memset(ft,0,sizeof(ft));
for(j=1; j<=i; j++)
ft[j]=f[j];//存储最初钓鱼量
ht=h;
for(j=1; j<i; j++)
ht-=t[j];//把走向下一个湖的时间减去
int k,emp=1;
while(ht>0&&emp<=i)
{
k=1;
for(j=emp; j<=i; j++)
if(ft[j]>ft[k])
k=j;
ans[i][0]+=ft[k];//加上最大的钓鱼量
++ans[i][k];//在这个湖里钓鱼的时间加一次
--ht;//拥有时间减去一次
ft[k]-=d[k];//鱼量减一次
ft[k]=ft[k]>0?ft[k]:0;//如果目前所剩鱼量小于0,赋值为0
for(j=emp; j<=i; j++)
{
if(ft[j]==0)
++emp;//统计有几个湖已经没有鱼
else
break;
}
}
if(ht>0)//如果还有时间就把鱼量加上
ans[i][1]+=ht;
}
int a=1;
for(i=2; i<=n; i++)//寻找最大值
if(ans[i][0]>ans[a][0])
a=i;
for(i=1; i<=n; i++)//输出每个湖所呆的时间
{
printf("%d",ans[a][i]*5);
if(i!=n)
printf(", ");
}
printf("\nNumber of fish expected: %d\n",ans[a][0]);
}
return 0;
}