子集和问题

这题的数组开的很调皮hhh
 

子集和问题

【问题描述】

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

【编程任务】

       对于给定的正整数的集合S={ x1, x2,…, xn}和正整数c,编程计算S 的一个子集S1,使得子集S1和等于c。

【输入格式】

       由文件subsum.in提供输入数据。文件第1行有2个正整数n和c,n表示S的个数,c是子集和的目标值。接下来的1 行中,有n个正整数,表示集合S中的元素。

【输出格式】

       程序运行结束时,将子集和问题的解输出到文件subsum.out中。当问题无解时,输出“No solution!”。

【输入样例】

5  10
2  2  6  5  4

【输出样例】

2  2  6

【代码】

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<iostream>
 4 #include<cstdlib>
 5 #include<cstring>
 6 #include<string>
 7 #include<cmath>
 8 
 9 using namespace std;
10 
11 int n,c,a[520],maxx,g,b[521],qwq[1314];
12 
13 int search(int,int);
14 int print(int);
15 
16 int main() {
17     cin>>n>>c;
18     for(int i=1; i<=n; i++) {
19         cin>>a[i];
20         maxx+=a[i];
21         qwq[a[i]]++;
22     }
23     if(c>maxx) { //绝对不可能的情况,可能不需要这一步,有的时候加一遍挺浪费时间 (数很大的时候);
24         cout<<"No solution!";
25         return 0;
26     } else search(1,c);
27     if(g==0) cout<<"No solution!";
28     return 0;
29 }
30 
31 int search(int x,int s) {
32     for(int i=1; i<=n; i++) {
33         if(a[i]<=c&&qwq[a[i]]) {
34             s-=a[i];
35             qwq[a[i]]--;
36             b[x]=a[i];
37             if(s==0) print(x);
38             else search(x+1,s);
39             s+=a[i];
40             b[x]=0;
41         }
42     }
43 }
44 
45 int print(int x) {
46     g++;
47     for(int i=1; i<=x; i++) {
48         cout<<b[i]<<" ";
49     }
50     cout<<endl;
51 }

 

posted @ 2017-03-24 20:31  夜雨声不烦  阅读(855)  评论(0编辑  收藏  举报