Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)ide
Problem Description - 題目描述測試
Jim has a balance and N weights. (1≤N≤20)
The balance can only tell whether things on different side are the same weight.
Weights can be put on left side or right side arbitrarily.
Please tell whether the balance can measure an object of weight M.spa
Jim 有一個天平和N塊砝碼。(1≤N≤20) 使用天平只能得知兩端質量是否相等。 砝碼能夠放置在左右任意一端。 判斷天平可否測量質量爲M的物體。
Input - 輸入code
The first line is a integer T(1≤T≤5), means T test cases.orm
For each test case :xml
The first line is N, means the number of weights.blog
The second line are N number, i'th number wi(1≤wi≤100)means the i'th weight's weight is wi.ip
The third line is a number M. M is the weight of the object being measured.ci
第一行有一個整數T(1≤T≤5),表示測試用例數。 對於每組測試用例: 第一行爲N,表示砝碼數。 第二行有N個數,第i個數wi(1≤wi≤100)表示 第三行有一個整數M。M爲待測物體質量。
Output - 輸出string
You should output the "YES"or"NO".
輸出"YES"or"NO"。
Sample Input - 輸入樣例
1 2 1 4 3 2 4 5
Sample Output - 輸出樣例
NO YES YES
Hint - 提示
For the Case 1:Put the 4 weight alone
For the Case 2:Put the 4 weight and 1 weight on both side
例子1:一端放置4
例子2:放置4和1在同一端
題解
DP水題,先算+,再算-,沒了。
代碼 C++
1 #include <cstdio> 2 #include <cstring> 3 #define MX 1500 4 bool dp[MX]; 5 int main() { 6 int t, n, i, j, data[25]; 7 scanf("%d", &t); 8 while (t--) { 9 scanf("%d", &n); 10 for (i = 0; i < n; ++i) scanf("%d", data + i); 11 memset(dp, 0, sizeof dp); dp[0] = 1; 12 for (i = 0; i < n; ++i) { 13 for (j = MX; ~j; --j) if (dp[j]) dp[j + data[i]] = 1; 14 } 15 for (i = 0; i < n; ++i) { 16 for (j = data[i]; j < MX; ++j) if (dp[j]) dp[j - data[i]] = 1; 17 } 18 scanf("%d", &n); 19 for (i = 0; i < n; ++i) { 20 scanf("%d", &j); 21 dp[j] ? puts("YES") : puts("NO"); 22 } 23 } 24 return 0; 25 }