본문 바로가기
알고리즘/그리디 알고리즘

knapsack 더블릿

by tryotto 2019. 2. 20.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <stdio.h>
#include <utility>
#include <vector>
#include <algorithm>
#include <functional>
 
using namespace std;
vector<pair<intfloat> > mon(2000);
 
bool compare(const pair<intfloat>& a, const pair<intfloat>& b) {
    if (a.second == b.second)
        return a.first > b.first;
    return a.second > b.second;
}
 
int main() {
    int w,n;    
    scanf("%d %d"&w, &n);
    getchar();
 
    for (int i = 1; i <= n; i++) {
        int a, b;
        scanf("%d %d"&a,&b);
        mon[i].first = a;
        mon[i].second = ((float) b / mon[i].first);
    }
    sort(&mon[1], &mon[n+1], compare);
        
    float rst=0;
    for (int i = 1; i <= n; i++) {
        if (w >= mon[i].first) {        
            w -= mon[i].first;
            rst += (mon[i].first * mon[i].second);
        }
        else if(w>0&&mon[i].first > w) {                
            rst += (w * mon[i].second);        
            w = 0;
        }        
    }
    printf("%.2f", rst);
}
cs


'알고리즘 > 그리디 알고리즘' 카테고리의 다른 글

테이블 옮기기 더블릿  (0) 2019.02.20
마감시간을 가지는 작업 더블릿  (0) 2019.02.20
mixing milk 더블릿  (0) 2019.02.20
(복습필요) 11000 강의실 배정  (0) 2019.02.19
1931 회의실 배정  (0) 2019.02.19