Fibonacci Knapsack
Description
We have N items, each with a specified weight and cost, and a bag that can carry a specified maximum weight. We want to place a subset of these items into the bag such that the total cost is maximized.
In this problem, the weights of the items are all Fibonacci numbers.
The first two Fibonacci numbers are 1 and 2. Each successive number is obtained by adding together the two previous numbers. Thus, the first Fibonacci numbers are 1, 2, 3, 5, 8, 13...
Input
The first line contains an integer T indicating the number of test cases.(1<=T<=20)
The first line of each test case contains two integers N and W (1<=N<=50), the number of items and the maximum weight that the bag can carry. Each of the following N lines contains two integers wi and ci( 1<=wi,ci <=10^16, wi will be a Fibonacci number), indicating the weight and cost of each item.
Output
You should output one line for each test case, containing the case number followed by the maximum total cost of the subset of items that can fit into the bag.
Sample Input
2
3 15
5 18
2 10
13 24
1 2
3 10
Sample Output
Case 1: 34
Case 2: 0
Source
modified from Topcoder SRM 352
/*算法思想:
DFS,先把所有的物品按照weight从大到小排序,weight相同的,按照cost从大到小排序
然后就是判断每个物品取不取
剪枝1:如果剩下的所有物品的cost之和小于作为answer的cost,不用搜索了
剪枝2:如果已经得到的合法的cost>ans,覆盖ans的值
剪枝3:要是上一个取了,这一个不管他和上一个的weight是什么关系,他可以取
要是上一个没有取那么只有他们的weight不同的情况下这个才能取
剪枝4:不管上一个取没有,不管他们的weight是什么关系,这一个都是可以不取的(这应该不算剪枝)
*/
/*CODE*/
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define N 60
using namespace std;
struct data
{
long long c,w;
} a[N];
long long t;
long long tot,ans,n;
long long sum[N];
/*DFS,搜索到了第v个物品,*/
void dfs(int v,bool last,long long last_w,long long last_c)
{
if(last_c+sum[n]-sum[v-1]<ans) return; //如果剩下的所有物品的cost之和小于作为answer的cost,退出
if(last_c>ans) ans=last_c; //如果已经得到的合法的cost>ans,覆盖ans的值
if(v>n) return; //已经找完了所有的物品
/*要是上一个取了,这一个不管他和上一个的weight是什么关系,他可以取
要是上一个没有取那么只有他们的weight不同的情况下这个才能取
*/
if(last_w+a[v].w<=tot && (last || (!last && a[v].w!=a[v-1].w)))
dfs(v+1,1,last_w+a[v].w,last_c+a[v].c);
/*然后不管上一个取没有,不管他们的weight是什么关系,这一个都是可以不取的*/
dfs(v+1,0,last_w,last_c);
}
bool cmp(data a,data b) //用于排序的比较函数
{
if(a.w!=b.w) return a.w>b.w;
return a.c>b.c;
}
int main()
{
scanf("%lld",&t);
for(int ca=1;ca<=t;ca++)
{
scanf("%lld%lld",&n,&tot);
memset(sum,0,sizeof(0));
for(int i=1;i<=n;i++) scanf("%lld%lld",&a[i].w,&a[i].c); //读入每个物品
sort(a+1,a+n+1,cmp); //按照weight从大到小排序,相同的weight按照cost从大到小排序
for(int i=1;i<=n;i++) sum[i]=sum[i-1]+a[i].c; //计算cost,sum[i]表示从1到i所有物品的cost之和
printf("Case %d: ",ca);
ans=0;
dfs(1,1,0,0);
printf("%lld\n",ans);
}
return 0;
}