Skip to content

Commit eff3b62

Browse files
committed
Weekly Contest 307
1 parent 4c21a2c commit eff3b62

4 files changed

+96
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Amount of Time for Binary Tree to Be Infected
2+
class Solution {
3+
int start, ans = 0;
4+
pair<int, int> dfs(TreeNode *x) {
5+
int h = 0, dep = x->val == start ? 0 : -1;
6+
for (auto *y : {x->left, x->right}) {
7+
if (!y) continue;
8+
auto [h1, dep1] = dfs(y);
9+
if (dep >= 0)
10+
ans = max(ans, dep+1+h1);
11+
else if (dep1 >= 0) {
12+
ans = max(ans, h+1+dep1);
13+
dep = dep1+1;
14+
}
15+
h = max(h, h1+1);
16+
}
17+
return {h, dep};
18+
}
19+
public:
20+
int amountOfTime(TreeNode* root, int start) {
21+
this->start = start;
22+
dfs(root);
23+
return ans;
24+
}
25+
};

find-the-k-sum-of-an-array.cc

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Find the K-Sum of an Array
2+
class Solution {
3+
public:
4+
long long kSum(vector<int>& a, int k) {
5+
long n = a.size(), sum = 0;
6+
for (int &x : a)
7+
if (x < 0)
8+
x = -x;
9+
else
10+
sum += x;
11+
sort(a.begin(), a.end());
12+
priority_queue<pair<long, int>> pq;
13+
pq.emplace(sum-a[0], 0);
14+
while (--k) {
15+
auto [s, i] = pq.top();
16+
sum = s;
17+
pq.pop();
18+
if (i+1 < n) {
19+
pq.emplace(s+a[i]-a[i+1], i+1);
20+
pq.emplace(s-a[i+1], i+1);
21+
}
22+
}
23+
return sum;
24+
}
25+
};

largest-palindromic-number.cc

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Largest Palindromic Number
2+
#define REP(i, n) for (long i = 0; i < (n); i++)
3+
#define ROF(i, a, b) for (long i = (b); --i >= (a); )
4+
5+
class Solution {
6+
public:
7+
string largestPalindromic(string num) {
8+
int c[10] = {};
9+
string ret;
10+
for (char x : num)
11+
c[x-'0']++;
12+
ROF(i, 0, 10) {
13+
if (i == 0 && ret.empty())
14+
continue;
15+
ret.insert(ret.end(), c[i]/2, '0'+i);
16+
c[i] %= 2;
17+
}
18+
int n = ret.size();
19+
ROF(i, 0, 10)
20+
if (c[i]) {
21+
ret.push_back('0'+i);
22+
break;
23+
}
24+
REP(i, n)
25+
ret += ret[n-1-i];
26+
return ret;
27+
}
28+
};
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// Minimum Hours of Training to Win a Competition
2+
#define REP(i, n) for (long i = 0; i < (n); i++)
3+
4+
class Solution {
5+
public:
6+
int minNumberOfHours(int a, int b, vector<int>& en, vector<int>& ex) {
7+
int n = en.size(), s = 0;
8+
REP(i, n) {
9+
if (a <= en[i])
10+
s += en[i]+1-a, a = en[i]+1;
11+
if (b <= ex[i])
12+
s += ex[i]+1-b, b = ex[i]+1;
13+
a -= en[i];
14+
b += ex[i];
15+
}
16+
return s;
17+
}
18+
};

0 commit comments

Comments
 (0)