[HDU] [2111] Saving HDU

Problem Description

Loading...

Problem Analysis

I originally thought of using Dynamic Programming
but sorting directly seems simpler for this problem…
Also, that Knapsack problem in the white book
seems like it can also be solved by sorting directly

cpp
 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
#include<stdio.h>
#include<algorithm>
using namespace std;
struct node {
	int p,m;
} a[120];
bool vs(node A,node B) {
	return A.p>B.p;
}
int main() {
	int v;
	while(scanf("%d",&v),v) {
		int n;
		scanf("%d",&n);
		for(int i=0; i<n; i++)
			scanf("%d %d",&a[i].p,&a[i].m);
		sort(a,a+n,vs);
		int sum=0,ti=0;
		while(v) {
			if(v>=a[ti].m) {
				sum+=a[ti].m*a[ti].p;
				v-=a[ti].m;
			} else {
				sum+=v*a[ti].p;
				v=0;
			}
			ti++;
			if(ti==n)
				break;
		}
		printf("%d\n",sum);
	}
	return 0;
}

Problem link: 【杭电】[2111]Saving HDU

Loading...