For many sets of consecutive integers from 1 through N (1 <= N <= 39), _disibledevent=>
- {3} and {1,2}
If N=7, there are four ways to partition the set {1, 2, 3, ... 7} so that each partition has the same sum:
- {1,6,7} and {2,3,4,5}
- {2,5,7} and {1,3,4,6}
- {3,4,7} and {1,2,5,6}
- {1,2,4,7} and {3,5,6}
Your program must calculate the answer, not look it up from a table.
PROGRAM NAME: subset
INPUT FORMAT
The input file contains a single line with a single integer representing N, as above.SAMPLE INPUT (file subset.in)
7OUTPUT FORMAT
The output file contains a single line with a single integer that tells how many same-sum partitions can be made from the set {1, 2, ..., N}. The output file should contain 0 if there are no ways to make a same-sum partition.SAMPLE OUTPUT (file subset.out)
4题目大意就是求讲数据1…N分成两组,使得两组中元素的和加起来相等,求这样分组的情况数
可以利用递推的方法求该题的解,注意:f(k,a)=(f(k-1,a+k)+f(k-1,a-k))/2;其中f(k,a)表示讲1…k元素分两组,使第一组比第二组多a;
因为k只可能分到第一组或第二组这两种情况,如果k加到第一组后使得第一组比第二组多a,则要原来的分组中第一组比第二组多a-k
同理如果k加到第二组后使得第一组比第二组多a,则要原来的分组中第一组比第二组多a+k。
因为交换两组元素后也满足条件,而只算一个解,故后面要除2;
很显然题目要求的是f(N,0);
为节省递推时间,可使用记忆化搜索,考虑到数据不大,又a有正负之分,可加数组适当开大。
1 /* 2 ID:shiryuw1 3 PROG:subset 4 LANG:C++ 5 */ 6 #include
最新评论