首页 > 其他 > 详细

HDU 2660 Accepted Necklace (DFS)

时间:2014-04-06 21:39:44      阅读:469      评论:0      收藏:0      [点我收藏+]

Accepted Necklace

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2474    Accepted Submission(s): 973


Problem 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
 

题意:给出宝石的数目n,制成项链所需的宝石个数k,然后再给出每个宝石的价值与重量,还有母亲会接受的最大重量,求出在小于等于最大重量范围内,项链的价值尽可能大。


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <climits>

const int MAX = 21;

typedef struct Stone{
	int value;
	int weight;
}Stone;

Stone stone[MAX];
int visit[MAX];
int maxv,limit,k,n;

void dfs(int v,int w,int x,int cnt){
	if(w>limit || cnt>k)return;
	if(cnt==k){
		if(v>maxv){
			maxv=v;
		}
		return;
	}
	int i;
	//这个地方下标直接从x开始,因为宝石并没有要求序列问题只是求价值和,所以不需要考虑重复情况,是个很大的剪枝
	//举例: 3 4 5 6 == 4 3 5 6 == 5 3 6 4虽然序列不同,但是价值和相同,这样的只需要搜一次即可也就是前面搜过的重量不再搜
	for(i=x;i<n;++i){
		if(visit[i]==0){
			visit[i]=1;
			dfs(v+stone[i].value,w+stone[i].weight,i,cnt+1);
			visit[i]=0;
		}
	}
}


int main(){

	int t,i;
	//freopen("in.txt","r",stdin);
    scanf("%d",&t);
	while(t-- && scanf("%d %d",&n,&k)!=EOF){
		for(i=0;i<n;++i){
			scanf("%d %d",&stone[i].value,&stone[i].weight);
		}
		scanf("%d",&limit);
		maxv = INT_MIN;
		memset(visit,0,sizeof(visit));
		for(i=0;i<n;++i){
			visit[i]=1;
			dfs(stone[i].value,stone[i].weight,i,1);
			visit[i]=0;
		}
		printf("%d\n",maxv);
	}
    return 0;
}




HDU 2660 Accepted Necklace (DFS),布布扣,bubuko.com

HDU 2660 Accepted Necklace (DFS)

原文:http://blog.csdn.net/iaccepted/article/details/23036963

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!