ACM-DFS之Accepted Necklace——hdu2660

Accepted Necklace

题目:http://acm.hdu.edu.cn/showproblem.php?pid=2660

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



依旧是DFS练习题,乍一看,我觉得像DP啊,后来看别人说多重背包也能解决,先用DFS做了吧,下次会了多重背包再解一次。
这道题,刚开始我考虑了很多:
用不用按照价值排序?  (去掉了时间上也没有变化)
有没有可能凑成的个数小于K,就是说如果要用3个石头凑成一根项链,两个石头的价值比其他三个石头的价值都大的情况。(发现也没有这种情况)
每次传递都要把搜到的位置传到下一个函数中,下一个函数从该位置向下搜索,否则  Must TLE.

代码:
#include <iostream>
#include <string.h>
using namespace std;
int max_wei,neck_num,n,va;
bool vis[21];

struct Stone
{
    int value,wei;
}sto[21];

// 注意,要将当前遍历到的位置向下传下去,否则会超时
void dfs(int js,int valu,int sum,int pre)
{
    if(js==neck_num)
    {
        va=valu>va?valu:va;
        return;
    }
    int i;
    for(i=pre;i<n;++i)
    {
        // 进行相应判断
        if(vis[i])  continue;
        if(sum+sto[i].wei<=max_wei)
        {
            vis[i]=1;
            dfs(js+1,valu+sto[i].value,sum+sto[i].wei,i);
            vis[i]=0;
        }
    }
}

int main()
{
    int i,total;
    cin>>total;
    while(total--)
    {
        // 输入相应数据
        cin>>n>>neck_num;
        for(i=0;i<n;++i)
            cin>>sto[i].value>>sto[i].wei;
        cin>>max_wei;
        memset(vis,0,sizeof(vis));

        va=0;
        dfs(0,0,0,0);
        cout<<va<<endl;

    }
    return 0;
}



你可能感兴趣的:(ACM,DFS,accepted,Necklace,hdu2660)