usaco Subset Sums

来源:互联网 发布:淘宝上的全球购物流 编辑:程序博客网 时间:2024/05/19 03:20

题意:给你一个n,代表有1到n个数。

求有多少对字串(假如每个串的和为A,B),A  = B = n个数的和 /  2。

我们可以求出所有满足要求的不同的串,串数除以2,便为答案。

dp[i][j]表示,前i个数,组成和为j有多少种方法。对于每一个数,我们有两种方案,选,那么dp[i][j] = dp[i - 1][j - num[i]], 不选,那么dp[i][j] = dp[i- 1][j]。

所以:当能够选,num[i] <= j .dp[i][j] = dp[i - 1][j - num[i]] + dp[i-1][j].否则dp[i][j] = dp[i - 1][j]。

这种01背包类型的还可以方便的,省空间复杂度,但本菜鸡就不管了。


/**ID: DickensToneLANG: C++TASK: subset**/#include<cstdio>#include<algorithm>#include<cstring>using namespace std;const int maxn = 40;const int Max_N = (1 + 40) * 40 / 2;long long dp[maxn][Max_N / 2];int n, half;int main(){    freopen("subset.in", "r", stdin);    freopen("subset.out", "w", stdout);    while(scanf("%d", &n) == 1)    {        dp[0][0] = 1;        half = (1 + n) * n / 2;        if(half == half / 2 * 2)        {            half = half / 2;            //printf("%d\n", half);            for(int i = 1; i <= n; i++)                for(int j = 0; j <= half; j++)                {                    if(j >= i) dp[i][j] = dp[i - 1][j - i] + dp[i - 1][j];                    else dp[i][j] = dp[i - 1][j];                }            printf("%d\n", dp[n][half] / 2);        }        else printf("0\n");    }    return 0;}


原创粉丝点击