zoukankan      html  css  js  c++  java
  • Equal Sum Sets

    题目链接:http://acm.hust.edu.cn/vjudge/problem/visitOriginUrl.action?id=49406

    题意:

          给出三个数 n,k,s;在不小于n的找到k个使其的和等于s的可能性有多少种。

         案例:

        input

         9 3 23

         9 3 22

         10 3 28

         16 10 107

         20 8 102

         20 10 105

         20 10 155

         3 4 3

         4 2 11

         0 0 0 

         output

         1 

         2

         0

         20

         1542

         5448

         1

         0

         0

    思路分析:

            利用dfs,尽可能的减少循环,第一次从1开始,第二次从2开始。。。。第n-1次n开始。找到所有可行解,当cur==k,sum==s,count++.

    原代码如下:

     1 #include<iostream>
     2 using namespace std;
     3 int n,k,s,count,a[25];
     4 void dfs(int cur)
     5 {
     6     if(k==cur)        //递归条件
     7     {
     8         int sum=0;
     9         for(int i=0;i<k;i++)
    10             sum+=a[i];
    11         if(sum==s)            //判断条件        
    12             count++;
    13     }
    14     int s=1;
    15     if(cur!=0)s=a[cur-1]+1;
    16     for(int j=s;j<=n;j++)
    17     {
    18         a[cur]=j;
    19         dfs(cur+1);
    20     }
    21 }
    22 int main()
    23 {
    24     cin>>n>>k>>s;
    25     while(n)
    26     {
    27         count=0;
    28         dfs(0);
    29         cout<<count<<endl;
    30         cin>>n>>k>>s;
    31     }
    32     return 0;
    33 }
  • 相关阅读:
    1033.采药1
    G——胜利大逃亡 (BFS)
    POJ 3278 Catch That Cow
    C
    11.17 dfs poj1979 Red and Black
    11.11反思
    kmp笔记
    dfs bfs
    1113
    python 类方法
  • 原文地址:https://www.cnblogs.com/q-c-y/p/4694438.html
Copyright © 2011-2022 走看看