题意:有n个石头,包含重量和价值,从中挑选最多k个石头做成一条项链,要求重量不大于W,求最大价值。
思路:dfs.
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2660
View Code
1 #include <cstdio> 2 #include <cstring> 3 #include <cstdlib> 4 #include <cmath> 5 #include <string> 6 #include <algorithm> 7 #include <iostream> 8 using namespace std; 9 const int N=21; 10 11 typedef struct In{ 12 int v; 13 int w; 14 }In; 15 In a[N]; 16 int n,k,w,MAX; 17 bool vis[N]; 18 19 void dfs(int s,int weight,int hight,int num){ 20 if(weight>w||num>k) return ; 21 MAX=max(MAX,hight); 22 for(int i=s+1;i<=n;i++){ 23 if(!vis[i]){ 24 vis[i]=true; 25 dfs(i,weight+a[i].w,hight+a[i].v,num+1); 26 vis[i]=false; 27 } 28 } 29 } 30 31 int main(){ 32 33 // freopen("data.in","r",stdin); 34 // freopen("data.out","w",stdout); 35 36 int t; 37 scanf("%d",&t); 38 while(t--){ 39 scanf("%d%d",&n,&k); 40 for(int i=1;i<=n;i++) 41 scanf("%d%d",&a[i].v,&a[i].w); 42 scanf("%d",&w); 43 memset(vis,false,sizeof(vis)); 44 MAX=0; 45 dfs(0,0,0,0); 46 printf("%d\n",MAX); 47 } 48 return 0; 49 }