topic description
You have a balance and N weights, and the weights of these N weights are W1, W2, · · ·, WN.
Please calculate how many different weights you can weigh in total?
Note that weights can be placed on both sides of the balance.
input format
The first line of input contains an integer N.
The second line contains N integers: W1, W2, W3, · · ·, WN.
output format
Output an integer representing the answer.
sample input
copy
3 1 4 6
sample output
copy
10
hint
【Example description】
The 10 weights that can be weighed are: 1, 2, 3, 4, 5, 6, 7, 9, 10, 11.
1 = 1;
2 = 6 4 (6 on one side of the balance and 4 on the other);
3 = 4 1;
4 = 4;
5 = 6 1; 6 =
6;
7 = 1 + 6;
9 = 4 + 6 1 ;
10 = 4 + 6;
11 = 1 + 4 + 6.
[Evaluation use case scale and agreement]
For 50% of the evaluation use cases, 1 ≤ N ≤ 15.
For all evaluation cases, 1 ≤ N ≤ 100, the total weight of N weights does not exceed 100000.
#include <iostream>
using namespace std;
const int N = 100009;
int w[109];
bool f[109][N];
int main() {
int n;
int sum = 0;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> w[i];
sum += w[i];
}
f[0][0] = true;//初始化
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= sum; j++) {//j代表重量
if (f[i - 1][j] == true) {
f[i][j] = true;//已有状态
f[i][j + w[i]] = true;//已有的基础上加的状态
if (j - w[i] > 0) {//已有的基础上减的状态
f[i][j - w[i]] = true;
}
else f[i][w[i] - j] = true;
}
}
}
int ans = 0;
for (int i = 1; i <= sum; i++) {
if (f[n][i]) {//统计最终状态
ans++;
}
}
cout << ans;
return 0;
}
More intuitively, there are the following diagrams
0 is used for initialization, so there is no need for statistics. Finally, the weight that can be weighed by the last weight is the total number