贪心算法之钓鱼

枚举在第i个湖结束钓鱼,那么花在路上的时间确定。贪心策略是每次在鱼剩余最多的地方钓鱼,如果有多个湖,则取编号最小的

出列,更新再入列

#include <iostream>
#include <stdio.h>
#include <memory.h>
#include <memory>
#include <math.h>
#include <algorithm>
#include <stdlib.h>
#include <queue>
using namespace std;
struct node
{
    int f,d,id,t;
    friend bool operator <(const node &a,const node &b)
    {
        if(a.f==b.f)
            return a.id > b.id;
        else
            return a.f < b.f;
    }
};
node fish[30];
priority_queue <node> q;
int n,T;
int Time[30];
int best[30];
int main()
{
    cin >> n;
    while(n!=0)
    {
        cin >> T;
        T*=12;
        for(int i=0; i<n; i++)
        {
            cin >> fish[i].f;
            fish[i].id = i;
        }
        for(int i=0; i<n; i++)
            cin >> fish[i].d;
        memset(Time,0,sizeof(Time));
        Time[0] = 0;
        for(int i=1; i<n; i++)
        {
            cin >> fish[i].t;
            Time[i] = fish[i].t;
            Time[i] += Time[i-1];
        }
        memset(best,0,sizeof(best));
        int maxfish=-1;/**注意,开始wa被这坑了**/
        for(int i=0; i<n; i++)
        {
            while(!q.empty())
                q.pop();
            for(int j=0; j<=i; j++)//只在前i个湖上钓鱼
                q.push(fish[j]);
            int fisht =0;
            fisht = T-Time[i];
            int temp[105];
            memset(temp,0,sizeof(temp));
            int numfish=0;
            while(fisht>0 && !q.empty())
            {
                node now = q.top();
                q.pop();
                fisht--;
                numfish+=now.f;
                now.f-=now.d;
                if(now.f<0)
                    now.f=0;
                temp[now.id]++;
                q.push(now);
            }
            if(numfish>maxfish)
            {
                maxfish = numfish;
                for(int k=0; k<n; k++)
                    best[k] = 5*temp[k];
            }
        }
        for(int i=0; i<n-1; i++)
            cout<<best[i]<<", ";
        cout<<best[n-1]<<endl;
        cout<<"Number of fish expected: "<<maxfish<<endl;
        cin >> n;
        if(n>0) cout<<endl;
    }

    return 0;
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页