2019_GDUT_ newborn Topics I anthology D HDU-2660

topic:

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

Practice: DFS, the current parameters passed by the stones, and the last time with a stone where every stone from the last start looking for used, or will time out. Because it is the first piece from the start dfs, so all combinations can be found. Dfs in two end conditions, a k is the stone has been used, one is already overweight.

Code:

#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;
	}
}
Published 14 original articles · won praise 0 · Views 306

Guess you like

Origin blog.csdn.net/qq_39581539/article/details/103964214