-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday42.cpp
More file actions
63 lines (50 loc) · 1.34 KB
/
day42.cpp
File metadata and controls
63 lines (50 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <vector>
#include <cmath>
#include <climits>
using namespace std;
int minPopulationDifference(int n, const vector<vector<int>>& grid) {
int total_cells = n * n;
vector<int> populations(total_cells);
int total_population = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
int index = i * n + j;
populations[index] = grid[i][j];
total_population += grid[i][j];
}
}
int target = total_population / 2;
vector<bool> dp(target + 1, false);
dp[0] = true;
for (int i = 0; i < total_cells; ++i) {
for (int s = target; s >= populations[i]; --s) {
dp[s] = dp[s] || dp[s - populations[i]];
}
}
int closest_sum = 0;
for (int s = target; s >= 0; --s) {
if (dp[s]) {
closest_sum = s;
break;
}
}
int diff = abs(total_population - 2 * closest_sum);
return diff;
}
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<vector<int>> grid(n, vector<int>(n));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cin >> grid[i][j];
}
}
cout << minPopulationDifference(n, grid) << endl;
}
return 0;
}