Greedy topic - Santa Claus gift

Examples of gifts Santa Claus

Distribute candy, boxes of different candy, each box has its own value and weight of each box can be split into any combination of bulk away, but can only hold W sled weight of candy, Santa Claus Will walk up to the enemy ah candy much value.
Input:
1⃣️n (box number) W (wt)
2⃣️n lines each box is given the value and weight (integer)
Output:
Maximum value (floating point)

Approach 1:
Value / descending order by weight, as the refill
o (nlogn) Sort

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<vector>
#include<string>
#define M 200000010
#define INF 0x3f3f3f3f
const double EPS = 1e-6;
using namespace std;
struct Candy{
    int v,w;
    bool operator < (const Candy &other)const{
        return double(v)/w - double(other.v)/other.w > EPS;
    }
}candies[100];
int main(){
    int n,w;
    cin >> n >> w;
    for(int i=0; i<n; i++){
        cin >> candies[i].v >> candies[i].w;
    }
    sort(candies,candies+10);
    double total_v=0,total_w=0;
    for(int i=0; i<n; i++){
        if(total_w+candies[i].w <= w){
            total_w += candies[i].w;
            total_v += candies[i].v;
        }
        else{
            total_v += candies[i].v * double(w-total_w)/candies[i].w;
            break;
        }
    }
    printf("%.2f\n",total_v);
    return 0;
}

Greedy algorithm, every move always follows a certain index to select the optimal operation carried out, the present, the future does not consider the impact caused.
Greedy algorithm needs to prove its correctness.
Santa Claus question, if the FCL can only get candy, then the greedy algorithm error
EG
. 8. 6
. 5. 5
. 5. 5
ski capacity 10

Published 62 original articles · won praise 0 · Views 1746

Guess you like

Origin blog.csdn.net/jhckii/article/details/104445470