返回题解分享
讨论 / 题解分享/ 帖子详情

砝码称重(编程题) - 题解

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

const int N = 110, M = 200010, B = M/2;
int a[N];
int n, m;
bool f[N][M];//从前i个砝码中选,重量为j的方案数

int main()
{
    cin >> n;
    for (int i = 1; i <= n; i ++ )
    {
        cin >> a[i];
        m += a[i];
    }
    
    f[0][B] = true;
    for (int i = 1; i <= n; i ++ )
        for (int j = -m; j <= m; j ++ )
        {
            f[i][j + B] = f[i - 1][j + B];
            if(j - a[i] >= -m) f[i][j + B] |= f[i - 1][j - a[i] + B];
            if(j + a[i] <= m)  f[i][j + B] |= f[i - 1][j + a[i] + B]; 
        }
        
    int res = 0;
    for (int j = 1; j <= m; j ++ )
        if(f[n][j + B] == true)
            res ++;
    cout << res;
    return 0;
}
0 回复 0 转发 1 喜欢 0 阅读
回复 (0)
默认 最新
暂无回复,快来抢沙发!