背包问题 codevs2210 数字组合

数字组合

题目描述 Description

在N个数中找出其和为M的若干个数。先读入正整数N和M, 再读入N个正数(可以有相同的数字,每个数字均在1000以内), 在这N个数中找出若干个数, 使它们的和是M, 把满足条件的数字组合都找出来以统计组合的个数,输出组合的个数(不考虑组合是否相同)。要求你的程序运行时间不超过1秒。

输入描述 Input Description

第一行是两个数字,表示N和M。
第二行起是N个数。

输出描述 Output Description

就一个数字,表示和为M的组合的个数。

样例输入 Sample Input

4 4
1 1 2 2

样例输出 Sample Output

3

数据范围及提示 Data Size & Hint

1<N<100

1<M<10000

 

大水题

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 int n,m;
 7 int f[10010],a[110];
 8 int main(){
 9     scanf("%d%d",&n,&m);
10     for(int i=1;i<=n;i++) scanf("%d",&a[i]);
11     f[0]=1;
12     for(int i=1;i<=n;i++)
13         for(int j=m;j>=0;j--)
14             if(f[j]&&j+a[i]<=m) f[j+a[i]]+=f[j];
15     printf("%d\n",f[m]);
16     return 0; 
17 }

 

posted @ 2017-07-11 23:12  zwube  阅读(244)  评论(0编辑  收藏  举报