Blue Bridge Cup Daily Question 2023.9.19

Lanqiao Cup 2021 Twelfth Provincial Competition Real Questions - Weight Weighing - C Language Network (dotcpp.com)

Question description

You have a balance and N weights. The weights of these N weights are W1, W2, · · · , WN.
Please calculate how many different weights can be weighed?
Note that the weights can be placed on both sides of the scale.

analyze

You can use DP to represent dp[i][j] as a set of solutions that only select the first i items and have a total weight of j. Its attribute is whether to select it (bool)

There are three options in total

Option 1: Do not select the i-th item

Option 2: Add the i-th item (put the i-th item on the right)

Option 3: Subtract the i-th item (subtract the i-th item)

Note: In order to prevent the label of the i-th item array from being negative, you need to add a value so that it is always a positive number.

#include<bits/stdc++.h>
using namespace std;
const int N = 110, M = 200010, b = M / 2;
int n, m, ans, w[N], dp[N][M];
int main()
{
	cin >> n;
	for(int i = 1; i <= n; i ++)
	{
		cin >> w[i];
		m += w[i];
	}
	dp[0][b] = 1;
	for(int i = 1; i <= n; i ++)
	{
		for(int j = -m; j <= m; j ++)
		{
			dp[i][j + b] = dp[i - 1][j + b];
			if(j - w[i] >= -m)dp[i][j + b] |= dp[i - 1][j - w[i] + b];
			if(j + w[i] <= m)dp[i][j + b] |= dp[i - 1][j + w[i] + b];	
		}
	}
	for(int i = 1; i <= m; i ++)
	{
		if(dp[n][i + b] == 1)ans ++;
	}
	cout << ans;
	return 0;
}

Guess you like

Origin blog.csdn.net/m0_75087931/article/details/133025039
Recommended