• 1764子集和问题(搜索算法)


    Description

    子集和问题的一个实例为〈S,t〉。其中,S={  x1 , x2 ,…,xn }是一个正整数的集合,c是一个正整数。子集和问题判定是否存在S的一个子集S1,使得:

    试设计一个解子集和问题的回溯法。
    对于给定的正整数的集合S={  x1 , x2 ,…,xn }和正整数c,计算S 的一个子集S1,使得:

    Input

    输入数据的第1 行有2 个正整数n 和c(n≤10000,c≤10000000),n 表示S 的大小,c是子集和的目标值。接下来的1 行中,有n个正整数,表示集合S中的元素。

    Output

    将子集和问题的解输出。当问题无解时,输出“No Solution!”。

    Sample

    Input 

    5 10
    2 2 6 5 4

    Output 

    2 2 6

    Hint

     1 #include <iostream>
     2 #include <algorithm>
     3 #include <string.h>
     4 #include <string>
     5 #include <map>
     6 
     7 using namespace std;
     8 
     9 int n, c, flag;
    10 int re[10005], a[10005];
    11 
    12 void op(int cur, int top, int sum)
    13 {
    14     if(flag || sum>c) return;
    15     else if(sum==c)
    16     {
    17         flag = 1;
    18         for(int i=0; i<top; i++)
    19         {
    20             if(i==top-1) cout << re[i] << endl;
    21             else cout << re[i] << " ";
    22         }
    23     }
    24     else
    25     {
    26         for(int i=cur; i<n; i++)
    27         {
    28             re[top] = a[i];
    29             op(i+1, top+1, sum+a[i]);
    30         }
    31     }
    32 }
    33 
    34 int main()
    35 {
    36     int sum, i;
    37     cin >> n >> c;
    38     for(i=0; i<n; i++)
    39     {
    40         cin >> a[i];
    41         sum += a[i];
    42     }
    43     if(sum < c) cout << "No Solution!" << endl;
    44     else
    45     {
    46         flag = 0;
    47         op(0, 0, 0);
    48         if(flag==0) cout << "No Solution!" << endl;
    49     }
    50     return 0;
    51 }
  • 相关阅读:
    WCF之ABC
    一次性为自定义实体类的数据填充
    在HttpHandlers中使用Session
    ASP.NET 2.0防止同一用户同时登陆
    Winson.Framework 1.5发布!
    SqlPager分页控件的使用!
    ExtJS 学习心得(一)
    [原创]Discuz!NT1.1高亮代码插件1.5稳定版!
    Winson.Framework 1.0发布!
    一个不错的WEB打印解决方案!
  • 原文地址:https://www.cnblogs.com/0xiaoyu/p/14098313.html
Copyright © 2020-2023  润新知