哈理工OJ 2004 整数划分(经典dp问题)

来源:互联网 发布:英雄连2 单位数据 编辑:程序博客网 时间:2024/05/21 12:05

题目链接:http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=2004

整数划分
Time Limit: 1000 MS Memory Limit: 32768 K
Total Submit: 143(109 users) Total Accepted: 115(104 users) Rating: Special Judge: No
Description
将正整数n表示成一系列正整数之和:n=n1+n2+…+nk,其中n1>=n2>=…>=nk>=1。正整数n的这种表示称为正整数n的划分。求正整数n的不同划分个数。例如,正整数6有如下11种不同的划分:6: 6; 5+1; 4+2; 4+1+1; 3+3; 3+2+1; 3+1+1+1; 2+2+2; 2+2+1+1; 2+1+1+1+1; 1+1+1+1+1+1.
Input
多组测试数据,输入到文件结束,每组数据包含一个正整数n(n<=40)
Output
输出n的不同划分个数。
Sample Input
3
6

Sample Output
3
11

Hint

Source
2014 Winter Holiday Contest 3

【题目分析】用dp[i][j]表示将i拆分成若干个数字,最大的那个数字不超过j的方案数。那么有两种情况,第一种是最后一个数不超过j-1,此时方案数是dp[i][j-1],否则数字刚好是j,此时方案数是dp[i-j][j],所以dp[i][j]=dp[i][j-1]+dp[i-j][j]。
最后的dp[n][n]就是答案。
【AC代码】

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;int dp[1005][1005];void init(int n,int m){    for(int i=1;i<=n;i++)    {        dp[i][1]=1;        dp[1][i]=1;    }    for(int i=2;i<=n;i++)    {        for(int j=2;j<=m;j++)        {            if(i==j)            {            dp[i][j]=dp[i][i-1]+1;            }            else if(i<j)            {                dp[i][j]=dp[i][i];            }            else            {                dp[i][j]=dp[i-j][j]+dp[i][j-1];            }        }    }}int main(){    int n;    init(40,40);    while(~scanf("%d",&n))    {        printf("%d\n",dp[n][n]);    }    return 0;}
0 0
原创粉丝点击