[Cpp]
# Include <iostream>
# Include <cstdio>
# Include <algorithm>
Using namespace std;
# Define MAXN 10
Struct Goods_Info
{
Int v; // Value
Int w; // weight
Double vw; // value-to-weight ratio
} Goods [MAXN];
Int n;
Int maxValue;
Bool solu [MAXN];
Bool optimalSolu [MAXN];
Bool Cmp (const Goods_Info a, const Goods_Info B)
{
Return a. vw> B. vw;
}
// The optimal value obtained when some items can be loaded
Double Bound (int I, double v, int c)
{
// Decrease the weight-to-weight ratio of an item and load it into a backpack
While (I <= n & goods [I]. w <= c)
{
V + = goods [I]. v;
C-= goods [I]. w;
I ++;
}
// Fill your backpack
If (I <= n)
{
V + = (goods [I]. vw * c );
}
Return v;
}
Void Backtrack (int k, int cv, int rc)
{
If (k> n)
{
If (cv> maxValue)
{
MaxValue = cv;
Int I;
For (I = 1; I <= n; I ++)
{
OptimalSolu [I] = solu [I];
}
}
}
Else
{
If (goods [k]. w <= rc) // whether the current item can be loaded into a backpack
{
Solu [k] = true;
Backtrack (k + 1, cv + goods [k]. v, rc-goods [k]. w );
}
If (Bound (k + 1, cv, rc)> maxValue) // whether the optimal value of remaining items is better
{
Solu [k] = false;
Backtrack (k + 1, cv, rc );
}
}
}
Int main (void)
{
Int c;
While (scanf ("% d", & n, & c )! = EOF)
{
Int I;
For (I = 1; I <= n; I ++)
{
Scanf ("% d", & goods [I]. v, & goods [I]. w );
Goods [I]. vw = (double) goods [I]. v/goods [I]. w;
}
// Sort items by value/weight ratio in descending order
Sort (goods + 1, goods + n + 1, Cmp );
MaxValue = 0;
Backtrack (1, 0, c );
Printf ("% d \ n", maxValue); // optimal value
/*
// Optimal Solution
Printf ("value :");
For (I = 1; I <= n; I ++)
{
Printf ("\ t % d", goods [I]. v );
}
Printf ("\ nweight :");
For (I = 1; I <= n; I ++)
{
Printf ("\ t % d", goods [I]. w );
}
Printf ("\ nstatus :");
For (I = 1; I <= n; I ++)
{
Printf ("\ t % d", optimalSolu [I]);
}
Printf ("\ n ");
*/
}
Return 0;
}
/*
5 27
8 3
12 7
10 5
8 4
15 9
5 27
8
12 12
10 10
8
15 15
5 26
8
12 12
10 10
8
15 15
5 28
8
12 12
10 10
8
15 15
5 29
8
12 12
10 10
8
15 15
*/