数的划分

题目描述

将整数n分成k份,且每份不能为空,任意两个方案不相同(不考虑顺序)。

例如:n=7,k=3,下面三种分法被认为是相同的。

1,1,5
1,5,1
5,1,1.

问有多少种不同的分法。

输入格式

n,k(6<n200,2k6)

输出格式

1个整数,即不同的分法。

输入输出样例

输入 #1
7 3
输出 #1
4

分析:
本题是一道极为经典的dfs题,由于k<=6,所以发现深搜的深度只需要6就可以了,而本题中dfs过程也较为好写。

CODE:
 1 #include<cmath>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<iostream>
 5 #include<algorithm>
 6 using namespace std;
 7 int n,k;
 8 long long tot;
 9 inline int get(){
10     char c=getchar();
11     int res=0,f=1;
12     while (c<'0'||c>'9') {
13         if (c=='-') f=-1;
14         c=getchar();
15     }
16     while (c>='0'&&c<='9'){
17         res=(res<<3)+(res<<1)+c-'0';
18         c=getchar();
19     }
20     return res*f;
21 }
22 void dfs(int now,int last,int all){
23     //cout<<now<<" "<<last<<" "<<all<<endl;
24     if (all>=n) return ;
25     if (now==k-1&&last>=n-all&&n-all>0) {/*cout<<"great"<<now<<" "<<last<<" "<<all<<endl;*/tot++;return ;}
26     if (now>=k) return ;
27     for (int i=1;i<=last;i++)
28         dfs(now+1,i,all+i);
29     return ;
30 }
31 int main() {
32     n=get(),k=get();
33     dfs(0,n,0);
34     cout<<tot<<endl;
35     return 0;
36 }


 
原文地址:https://www.cnblogs.com/kanchuang/p/11337720.html