zzuli2424: 越靠近,越幸运(dfs)

http://acm.zzuli.edu.cn/problem.php?id=2424

题目描述

对于普通数字来说,越接近幸运数字,也会变得越幸运。
已知幸运数字X,现存在N个普通数字,他们为了变得更幸运,通过组和的方式来尝试靠近幸运数字X。请问他们通过组和的方式获得最幸运的数字是多少?幸运数字不喜欢比它大的数字,即:组和成的数字如果大于幸运数字,它不会变的幸运。

输入

测试实例包括T组测试数据。(T <= 100)
每组测试数据第一行为两个数字X和N,第二行为N个普通数字。(0 <= X <= 1e6, 0 < N <= 10, 0 <= 普通数字 <= 1e6, 涉及到的所有数字均为整数)

输出

对于每组测试数据,输出可以获得的最幸运的数字。不存在最幸运的数字,输出-1

样例输入 Copy

3
50 2
25 26
5 4
2 3 4 6
1 1
5

样例输出 Copy

26
5
-1

给出的每个数字都有两个可能:选或不选。

深搜找出最接近X的数即可。

#include<stdio.h>
#include<string.h>
#define N 20
int a[N];
int x,ans,m,n,book;
void dfs(int s)
{
    int i;
	if(s == n+1)
		return ;
	for(i=0; i<=1; i++)
    {
        m+=i*a[s];
        if(m > ans && m<=x)
        {
            ans=m;
            book=1;
        }

        dfs(s+1);
        m-=i*a[s];
    }
}
int main()
{
	int t,i;
	scanf("%d",&t);
	while(t--)
	{
		ans=0;
		m=0;
		book=0;
		memset(a, 0, sizeof(a));
		scanf("%d%d", &x, &n);
		for(i=1; i<=n; i++)
			scanf("%d", &a[i]);
		dfs(1);
		if(book)
            printf("%d\n",ans);
        else
            printf("-1\n");
	}
	return 0;
}

 

posted @ 2019-03-21 16:08  宿星  阅读(89)  评论(0编辑  收藏  举报