Sumsets
Time Limit: 2000MS | Memory Limit: 200000K | |
Total Submissions: 21236 | Accepted: 8264 |
Description
Farmer John commanded his cows to search for different sets of numbers that sum to a given number. The cows use only numbers that are an integer power of 2. Here are the possible sets of numbers that sum to 7:
1) 1+1+1+1+1+1+1
2) 1+1+1+1+1+2
3) 1+1+1+2+2
4) 1+1+1+4
5) 1+2+2+2
6) 1+2+4
Help FJ count all possible representations for a given integer N (1 <= N <= 1,000,000).
1) 1+1+1+1+1+1+1
2) 1+1+1+1+1+2
3) 1+1+1+2+2
4) 1+1+1+4
5) 1+2+2+2
6) 1+2+4
Help FJ count all possible representations for a given integer N (1 <= N <= 1,000,000).
Input
A single line with a single integer, N.
Output
The number of ways to represent N as the indicated sum. Due to the potential huge size of this number, print only last 9 digits (in base 10 representation).
Sample Input
7
Sample Output
6
个人理解:
如果i为奇数,肯定有一个1,把f[i-1]的每一种情况加一个1就得到f[i],所以f[i]=f[i-1];
如果i为偶数,如果有1,至少有两个,则f[i-2]的每一种情况加两个1,就得到i,此时f'=f[i-2]
如果没有1,则把分解式中的每一项除2,和f[i/2]的情况一一对应 则得到f''=f[i/2]
综上:f[i]=f[i-2]+f[i/2]
代码通过情况:
代码:
# include<stdio.h>
# define mod 1000000000
# define MAX 1000001
int a[MAX]={1,1,2},i;
int main()
{
for(i=2;i<MAX;a[i+1]=a[i],i+=2)
a[i]=(a[i-2]+a[i>>1])%mod;
scanf("%d",&a[0]);
printf("%d\n",a[a[0]]);
return 0;
}
_____________________________________另一个动态规划:
/*有N个同种类的物品,将它划分为不超过M组 求划分的方法的总数
限制:N,M∈[1,100];
EG:
输入N=4
M=3
输出:4 //1+1+2=1+3=2+=4 共四种
解:DP问题
定义DP[i][j]存储 j的i划分的总数
如果我们将j划分为i个的话,可以先取出K个,然后将剩下的j-k个分成i-1份
这样就有 DP[i][j]=∑dp[i-1][j-k] 求和为k=0到k=j求和
但是这样就会出现重复问题
比如上面的例子 如果用这种方式求 那么1+1+2 和1+2+1就会被当作不同的式子 结果就会出错
我们设 Ai为划分过程中出现的数
则 N的M划分 可以为表示为
A1+A2+A3+……+Am=N Ai共M项
GGG1:如果对应的每个Ai都满足Ai>0 则
等式A1+A2+A3+……+Am=N 两边都减去M 有
(A1-1)+(A2-1)+(A3-1)+……+(Am-1)=N-M
上式子相当于N-M的M划分
GGG2:如果对应的Ai中存在Ai=0 则 将其定义为N的M-1划分
比如A1+A2+A3+……+Am=N中
A1 A2 A3 全为0
则 可以将其表示为
N的M-1划分 (此时去掉A1)
N的M-2划分 (此时去掉A2)
N的M-3划分 (此时去掉A3)
……
直至里面没有Ai=0 去掉的顺序无所谓 只要最终去掉所有的0
也就是说
A1+A2+A3+……+Am+0+0+0+……+0=N 无论里面有多少0 这个式子对应的划分数和A1+A2+A3+……+Am=N 是一样的
综合GGG1 2 有
DP[i][j]=DP[i][j-i]+DP[i-1][j]
时间复杂度O(NM)
*/
# include <stdio.h>
# define MAX 101
int DP[MAX][MAX]={1,0},i,j,M,N;
int main(){
scanf("%d%d",&N,&M);
for(i=1;i<=M;i++)
for(j=0;j<=N;j++)
if(j-i>=0)
DP[i][j]=DP[i-1][j]+DP[i][j-i];
else
DP[i][j]=DP[i-1][j];
printf("%d\n",DP[M][N]);
return 0;
}