Main topic:
There are n cows eating in the FJ garden.
So FJ to drive them back to the barn.
Each cow eats a di flower every second before being driven away. To drive it back to FJ to spend time is ti, go back to catch other cows also need ti time. In the process of being driven away, cows can't eat.
Topic Link: Click to open the link
Analysis: This problem is similar to the knapsack problem in the heart of greed, it is related to the ratio problem, according to the ratio to sort. The knapsack problem is in the order of value/quality from the big to the small, and here we d/t from the big to the small sort, in this sequence to catch the cattle.
Here is the proof:
Set Di,ti,ti respectively for the number I (to di/ti from large to small number) of cattle per second to eat di a flower, the time to drive it is Ti, after ti time to be driven away, we first consider the Cow 1
For cattle 1 There are d1/t1 > dk/tk (1<k<=n), i.e. D1 * tk > DK * T1
① According to the greedy thought above, then the Ox 1 must be first driven away. The total cost at this time is:
D1*t1+d2*t2.......+dn*tn = D2*t2.......+dn*tn because t1=0
② if not first to catch cattle 1, then we exchange cattle 1 and the order of cattle I. The total cost of the time has changed.
1. For the cow after the cow I, its t is unchanged
2. For cow 1,t1 ' = T1+t2+t3.....+ti = T2+t3.....+ti
3. For cattle i, Ti ' = 0
4. For cattle numbered between 1 and I, Tk ' = tk+ (TI-T1)
So the total cost at this time is:
d1*t1 ' +d2*t2 ' ... +dn*tn ' = ( d2*t2.......+dn*tn) + (D1*t2+d1*t3...+d1*ti) + (D2*ti+d3*ti...+di-1*ti)-(d2*t1+d3*t1...+ DI-1*T1) &NBSP;
Because d1 * tk > DK * T1, so (d1*t2+d1*t3...+d1*ti-1)-(D2*T1+D3*T1...+DI-1*T1) >0
So spend 2 > spend 1
To sum up, we know that this greedy method is correct.
Attached code:
#include <iostream> #include <algorithm>using namespace std;struct cow{int T, D; Cow (int a = 0, int b = 0) {T = a, d = b;}} cow[100000 + 5];long long ans, sum;int n;bool cmp (cow &a, cow &b) {return A.D * b.t > B.D * A.T;} In order to avoid the accuracy error caused by the division to produce decimals, we take the form of the multiplication int main () {scanf ("%d", &n); for (int i = 1; I <= n; i++) scanf ("%d%d", &cow[i].t, &A MP;COW[I].D); sort (cow + 1, cow + n + 1, CMP), for (int i = 1; I <= n; i++) {sum + = cow[i-1].t * 2; Back and forth altogether twice times tans + = sum * COW[I].D;} printf ("%lld\n", ans); return 0;}
(water) POJ-3262 greedy, backpack, ratio problem