forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
35 lines (35 loc) · 934 Bytes
/
Solution.cpp
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
class Solution {
public:
int minTransfers(vector<vector<int>>& transactions) {
int g[12]{};
for (auto& t : transactions) {
g[t[0]] -= t[2];
g[t[1]] += t[2];
}
vector<int> nums;
for (int x : g) {
if (x) {
nums.push_back(x);
}
}
int m = nums.size();
int f[1 << m];
memset(f, 0x3f, sizeof(f));
f[0] = 0;
for (int i = 1; i < 1 << m; ++i) {
int s = 0;
for (int j = 0; j < m; ++j) {
if (i >> j & 1) {
s += nums[j];
}
}
if (s == 0) {
f[i] = __builtin_popcount(i) - 1;
for (int j = (i - 1) & i; j; j = (j - 1) & i) {
f[i] = min(f[i], f[j] + f[i ^ j]);
}
}
}
return f[(1 << m) - 1];
}
};