NBUT1479:How many(DFS)

http://ac.nbutoj.com/Problem/view.xhtml?id=1479

 

  • 问题描述
  • There are N numbers, no repeat. All numbers is between 1 and 120, and N is no more than 60. then given a number K(1 <= K <= 100). Your task is to find out some given numbers which sum equals to K, and just tell me how many answers totally,it also means find out hwo many combinations at most.
  • 输入
  • There are T test cases.
    For each case:
    First line there is a number N, means there are N numbers.
    Second line there is a number K, means sum is K.
    Third line there lists N numbers.
    See range details in describe.
  • 输出
  • Output the number of combinations in total.
  • 样例输入
  • 2
    5
    4
    1,2,3,4,5
    5
    6
    1,2,3,4,5
    
  • 样例输出
  • 2
    3
    
    题意:给出n个数,要找出加起来等于k的方法有几种,要注意,1+2 = 3 与2+1=3,这是一样的情况
    思路:与杭电SUM IT UP那道题是一样的,果断DFS
     
    #include <stdio.h>
    #include <algorithm>
    #include <string.h>
    using namespace std;
    
    int a[1000],n,m,cnt;
    
    int cmp(int a,int b)
    {
        return a>b;
    }
    
    void dfs(int pos,int sum)
    {
        int i;
        if(sum>m)
            return ;
        if(sum == m)
            cnt++;
        for(i = pos; i<n; i++)
        {
            dfs(i+1,sum+a[i]);
            while(i+1<n && a[i] == a[i+1])
                i++;
        }
    }
    
    int main()
    {
        int t,i;
        scanf("%d",&t);
        while(t--)
        {
            scanf("%d%d",&n,&m);
            for(i = 0; i<n-1; i++)
                scanf("%d,",&a[i]);
            scanf("%d",&a[i]);
            sort(a,a+n,cmp);
            cnt = 0;
            dfs(0,0);
            printf("%d\n",cnt);
        }
    
        return 0;
    }
    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值