UVa 1213

easy 0-1 knapsack problem
state:
    dp[i][j] - how many ways to form integer i using j primes
transition:
    dp[i][j]+=dp[i-p[k]][j-1], for all j from 1 to 14
a trick to generate primes table is also used here
/* UVas */
/*****************************************************************************/
#define N 1121
#define K 15
#define P 187
int n, k;
int d[N][K]={};
int m[N];
int p[P];
int main(void) {
    p[0]=2;
    for (int i=2; i*i<N; i++)
        for (int j=i+i; j<N; j+=i)
            m[j]=1;
    for (int i=2, j=0; i<N; i++)
        if (!m[i])
            p[j++]=i;
    d[0][0]=1;
    for (int i=0; i<P; i++)
        for (int j=N-1; j>=p[i]; j--)
            for(int l=1; l<K; l++)
                d[j][l]+=d[j-p[i]][l-1];
    while (scanf("%d %d", &n, &k)>0&&n&&k) {
        printf("%d\n", d[n][k]);
    }
}
/*****************************************************************************/

No comments :

Post a Comment