称砝码(动态规划实现)

牛客网称砝码编程题:

#include <stdio.h>

int main(){
    int n;
    while(scanf("%d",&n)!=EOF){
        int i,j,m,total=0,sum,count=0;
        int weight[n];
        for(i=0;i<n;i++)
            scanf("%d", &weight[i]);
        int nums[n];
        for(j=0;j<n;j++)
            scanf("%d", &nums[j]);
        for(i=0;i<n;i++){
            total += weight[i]*nums[i];
        }
        sum=total;
        int temp[n+1][sum+1];
        for(i=0;i<=n;i++)
            for(j=0;j<=sum;j++)
                temp[i][j]=0;
        for(i=1;i<=n;i++){
            for(j=0;j<=total;j++){
                if(temp[i-1][j]==1){
                    temp[i][j]=1;
                }
                else{
                    for(m=1;m<=nums[i-1];m++)
                        if(j>m*weight[i-1] && temp[i-1][j-m*weight[i-1]]==1)
                            temp[i][j]=1;
                        else if(j==m*weight[i-1])
                            temp[i][j]=1;

                }
            }
        }
        for(i=0;i<=total;i++)
            if(temp[n][i]==1)
                count++;
        printf("%d\n",++count);
    }
    return 0;
}

 

点赞