2019_GDUT_新生专题I选集 D HDU-2660

题目:

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,传递的参数是当前用了几块石头,以及上一次用到哪一块石头,每次从上次用的石头开始查找,不然会超时。因为是从第一块开始dfs的,所以所有的组合都能找到。在dfs结束条件有两个,一个是已经用了k块石头,一个是已经超重。

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int n,k,a[30],b[30],w,ans,c[30],val,wei;

void dfs(int x,int K)
{
	if (x>k || wei>w) return;
	if (x==k && val>ans)
	ans=val;
	else
	{
		for (int i=K;i<=n;i++)
		{
			if (!c[i])
			{
				c[i]=1;
				wei+=b[i];
				val+=a[i];
				dfs(x+1,i);
				wei-=b[i];
				val-=a[i];
				c[i]=0;
			}
		}
	}
}

int main()
{
	int T;
	cin>>T;
	while (T--)
	{
		ans=0;
		val=wei=0;
		memset(c,0,sizeof(c));
		cin>>n>>k;
		for (int i=1;i<=n;i++)
		cin>>a[i]>>b[i];
		cin>>w;
		dfs(0,0);
		cout<<ans<<endl;
	}
}
发布了14 篇原创文章 · 获赞 0 · 访问量 306

猜你喜欢

转载自blog.csdn.net/qq_39581539/article/details/103964214