Accepted Necklace【DFS】

题目描述:原题链接

Description
I have N precious stones, and plan to use K of them to make a necklace for my mother, but she won’t accept a necklace which is too heavy. Given the value and the weight of each precious stone, please help me find out the most valuable necklace my mother will accept.

Input
The first line of input is the number of cases.
For each case, the first line contains two integers N (N <= 20), the total number of stones, and K (K <= N), the exact number of stones to make a necklace.
Then N lines follow, each containing two integers: a (a<=1000), representing the value of each precious stone, and b (b<=1000), its weight.
The last line of each case contains an integer W, the maximum weight my mother will accept, W <= 1000.

Output
For each case, output the highest possible value of the necklace.

Sample Input
1
2 1
1 1
1 1
3

Sample Output
1

思路:

标准DFS,同时判断重量和个数的限制,不断更新的到解。

#include 
#include 
using namespace std;
struct Stone
{int v,w;
}s[30];
int n,k,maxn,weight;
int vis[30];
void dfs(int cnt,int val,int wgt,int step)
{if(cnt==k||weight==wgt){if(val>maxn)maxn=val;return;}for(int i=step;i<n;i++){if(!vis[i]&&cnt+1<=k&&wgt+s[i].w<=weight){vis[i]=1;dfs(cnt+1,val+s[i].v,wgt+s[i].w,i+1);vis[i]=0;}}
}
int main()
{int T;scanf("%d",&T);while(T--){memset(vis,0,sizeof(vis));scanf("%d%d",&n,&k);for(int i=0;i<n;i++)scanf("%d%d",&s[i].v,&s[i].w);scanf("%d",&weight);maxn=0;dfs(0,0,0,0);printf("%d\n",maxn);}return 0;
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部