Skip to content

Commit 4d3452f

Browse files
committed
Update code
1 parent 3993aa4 commit 4d3452f

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

bookcode/triangle.cc

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#include "../xxx.h"
2+
3+
int cnt(vector<int> &edges) {
4+
int sz = edges.size();
5+
int ret = 0;
6+
for (int i = 0; i < sz; i++) {
7+
for (int j = i + 1; j < sz; j++) {
8+
for (int k = j + 1; k < sz; k++) {
9+
int sum = edges[i] + edges[j] + edges[k];
10+
int max_len = max({edges[i], edges[j], edges[k]});
11+
int tw_sum = sum - max_len;
12+
if (tw_sum > max_len) {
13+
ret++;
14+
}
15+
}
16+
}
17+
}
18+
19+
return ret;
20+
}
21+
22+
int main(int argc, char *argv[]) {
23+
vector<int> edges;
24+
return 0;
25+
}

cc/rearranging-fruits.cc

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// https://leetcode.com/problems/rearranging-fruits/
2+
#include "xxx.hpp"
3+
4+
class Solution {
5+
public:
6+
long long minCost(vector<int> &basket1, vector<int> &basket2) {
7+
map<int, int> cnt;
8+
for (auto &num : basket1) {
9+
cnt[num]++;
10+
}
11+
for (auto &num : basket2) {
12+
// not plus, minus
13+
// means the one with zero value is kept in this array
14+
cnt[num]--;
15+
}
16+
vector<int> exch;
17+
for (auto &kv : cnt) {
18+
// odd count, can not split
19+
if (kv.second & 1) {
20+
return -1;
21+
}
22+
for (int i = 0; i < abs(kv.second) / 2; i++) {
23+
exch.push_back(kv.first);
24+
}
25+
}
26+
int sz = exch.size();
27+
nth_element(exch.begin(), exch.begin() + sz / 2, exch.end());
28+
int minx = min(*min_element(basket1.begin(), basket1.end()),
29+
*min_element(basket2.begin(), basket2.end()));
30+
31+
// Within each pair, there are two exchange methods:
32+
// 1. Direct exchange, the cost is the smaller number.
33+
// 2. Indirect exchange, choose another small number xxx as the
34+
// "intermediate", swap ai with x ans x with bj, the cost is 2x
35+
return accumulate(exch.begin(), exch.begin() + sz / 2, 0ll,
36+
[&](long long acc, int cur) -> long long {
37+
return acc + min(2 * minx, cur);
38+
});
39+
}
40+
};
41+
42+
int main(int argc, char *argv[]) {
43+
Solution so;
44+
vector<int> input1{4, 2, 2, 2};
45+
vector<int> input2{1, 4, 1, 2};
46+
cout << so.minCost(input1, input2) << endl;
47+
return 0;
48+
}

0 commit comments

Comments
 (0)