Problem description
A set of n elements {1, 2,..., n} can be divided into several non-empty subsets. For example, when n = 4, the set {1, 2, 3, 4} can be divided into 15 different non-empty subsets as follows:
{1}, {2}, {3}, {4 }}, {1, 2}, {3}, {4 }}, {1, 3 }, {2}, {4 }},{ {}, {2}, {3 }},{ 2, 3}, {1}, {4 }}, {2, 4}, {1}, {3 }}, {3, 4}, {1}, {2 }}, {1, 2}, {3, 4 }}, {1, 3}, {2, 4}, {1, 4}, {2, 3}, {4 },{ 1, 2, 4 }, {3 }},{ 1, 3}, {2 }},{ 2, 3, 4}, {1 }},{ 1, 2, 3, 4 }}
Given a positive integer N (1 <= n <= 20), calculate the number of different non-empty subsets of the set of n elements {,..., n.
Input Multiple groups of input data. one row of each group of data indicates the number of elements N. Output outputs one row for each group of data, indicating the number of different non-empty subsets. Sample input24 sample output215 sourcefoj monthly competition-August 1, March 2008
Solution:
The second type of Stirling Number S (P, K) is the number of unidentifiable non-empty boxes that divide the set of P elements into K.
(P different balls, put K in the same box, no empty box is allowed)
Recurrence relationship:
S [p] [0] = 0 (P> = 1), s [p] [1] = 1 (P> = 0)
S [p] [k] = s [P-1] [k-1] + K * s [P-1] [K].
Note that int is easily out of the range. When P is 20, it is out of the int range type.
Code:
# Include <iostream> # include <string. h> using namespace STD; const int maxn = 21; typedef long ll; ll s [maxn] [maxn]; ll ans [maxn]; // divide the elements of the I type into 0, 1, 2, 3 ,... total number of non-empty set in I-1 int N; void Init () {memset (S, 0, sizeof (s); memset (ANS, 0, sizeof (ANS )); s [1] [1] = 1; for (INT I = 2; I <= 20; I ++) for (Int J = 1; j <= I; J + +) s [I] [J] = s [I-1] [J-1] + J * s [I-1] [J]; for (INT I = 1; I <= 20; I ++) for (Int J = 1; j <= I; j ++) ans [I] + = s [I] [J];} int main () {Init (); While (CIN> N) {cout <ans [N] <Endl ;} return 0 ;}