本题练习贪心:
题目链接:http://poj.org/problem?id=1042
本题的解题思路是枚举+ 贪心。
分析:一旦最后到达的湖确定,所有涉及t[i]的和就是一个定值。
所以,可以枚举最后到达的湖,每次枚举过程中,采用贪心的思路:选择目前的能一次钓到的最大鱼量即可。
总体的时间复杂度为O(k n^2)
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
using namespace std;
int fi[30];
int di[30];
int ti[30];
int record[30];
int sum;
int left_time;
int n,h;
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
int test = 0;
while(scanf("%d",&n)!=EOF && n!=0)
{
test++;
if(test!=1)
{
printf("\n");
}
sum = -1;//注意这里初始化不能是0,因为有可能刚开始所有湖的鱼都是0.
left_time = 0;
memset(record,0,sizeof(record));
scanf("%d",&h);
h *= 12;
for(int i=0; i<n; i++)
{
scanf("%d",&fi[i]);
}
for(int i=0; i<n; i++)
{
scanf("%d",&di[i]);
}
ti[0] = 0;
for(int i=1; i<n; i++)
{
scanf("%d",&ti[i]);
ti[i] += ti[i-1];
}
for(int i=0; i<n; i++)
{
left_time = h - ti[i];
int max = 0;
int fi_temp[30];
int record_temp[30];
int sum_temp = 0;
memcpy(fi_temp,fi,sizeof(fi));
memset(record_temp,0,sizeof(record_temp));
while(left_time>0)
{
max = 0;
int flag = 0;
int j_temp = 0;
for(int j=0; j<=i; j++)
{
if(fi_temp[j]>max)
{
flag = 1;
max = fi_temp[j];
j_temp = j;
}
}
if(flag == 0)
{
break;
}
record_temp[j_temp]++;
sum_temp += max;
fi_temp[j_temp] -= di[j_temp];
left_time--;
}
if(left_time>0)
{
record_temp[0] += left_time;
}
if(sum_temp>sum)
{
sum = sum_temp;
memcpy(record,record_temp,sizeof(record_temp));
}
}
for(int i=0; i<n; i++)
{
if(i == n-1)
{
printf("%d\n",record[i] * 5);
}
else
{
printf("%d, ",record[i] * 5);
}
}
printf("Number of fish expected: %d\n",sum);
}
return 0;
}