链接:点击打开链接
题意:给出n个宝石,输入n个宝石的价值和重量,问选出k颗并且总重量不超过w时所产生的最大价值是多少
代码:
#include <iostream> #include <stdio.h> #include <string.h> #include <climits> #include <algorithm> using namespace std; int t,n,k,w,ans; int a[1005],b[1005],vis[1005]; void dfs(int u,int num,int value,int weight){ int i; if(num==k){ if(value>ans) ans=value; return; } for(i=u;i<n;i++){ if(weight+b[i]<=w&&num+1<=k){ vis[i]=1; dfs(i+1,num+1,value+a[i],weight+b[i]); vis[i]=0; } } } //dfs深搜 int main(){ int i; scanf("%d",&t); while(t--){ ans=0; scanf("%d%d",&n,&k); memset(vis,0,sizeof(vis)); for(i=0;i<n;i++) scanf("%d%d",&a[i],&b[i]); scanf("%d",&w); dfs(0,0,0,0); printf("%d\n",ans); } return 0; }