init: init commit, build

This commit is contained in:
Oyasuminasai
2025-12-29 14:13:38 +08:00
commit 455cabe243
207 changed files with 39618 additions and 0 deletions

View File

@@ -0,0 +1,126 @@
---
tags:
- Greedy
- Heap
date: 2025-12-22
---
[Leetcode Question Link](https://leetcode.com/problems/maximize-happiness-of-selected-children/?envType=daily-question&envId=2025-12-25)
For the convenience, we use $a[i]$ to denote $\text{happiness}[i]$ in article below.
# Analysis
## Gain From One Child
Consider if we chose children $i$ at time $t, \;t \in [0, k)$, what could we add to the final sum?
If not considering our choice, the lost of the happiness $L$ should be:
$$
L(i) = min(a[i], k)
$$
- If $a[i] \le k$, this means the $a[i]$ will goes to $0$ before the procedure finished, so the maximum decrease of the value is from $a[i]$ to $0$, that is, $L = a[i]$
- If $a[i] > k$, that means $a[i]$ never reach $0$, the decrease value is exactly the round $k$. So we have $L = k$.
Now take our choice operation into consideration. If we chose a child at time $t$, then the actual lost of happiness of this child should be:
$$
L_{A}(i, t) = min(L(i), t)
$$
- If $t < L$, means we chose this child while it's decreasing, this means if we chose this child, it should be decreasing from time $0$ to time $t$, the actual decrease value $L_{A} = t$.
- If $t > L$, means this child's happiness already stop decreasing, our action of choice actually has no effect, so $L_{A} = L$.
-----
In conclusion, we could know that for any child $i$, if we choice it, the happiness value $H$ we could get will be:
$$
\begin{align}
H(i, t) &= a[i] - L_{A}(i, t) \\[1em]
&= a[i] - min(min(a[i], k), t) \\[1em]
&= a[i] - min(a[i], k, t)
\end{align}
$$
## Choose Child
Based on analysis above, we should be aware that the greedy strategy could be used for this question. That is, **to ensure highest final sum, we should always choose child with largest initial happiness first**.
Consider the formula of $H(i, t)$:
$$
H(i, t) = a[i] - min(a[i], k, t)
$$
If we want to make $H(i, t)$ larger, we need to make $min(a[i], k, t)$ smaller, so we should put larger $a[i]$ with smaller $t$. And that, in this problem, means choose child with larger happiness sooner.
# Code
```cpp
#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
using std::priority_queue;
using std::vector;
bool debug = false;
struct MyMinHeap : std::priority_queue<int, std::vector<int>, std::greater<int>> {
void reserve(size_t n) { this->c.reserve(n); }
};
class Solution {
public:
long long maximumHappinessSum(vector<int>& happiness, int k) {
// min heap
MyMinHeap maxk;
maxk.reserve(k);
int cur, top;
// initial heap with k elements
for (int i = 0; i < k; ++i) {
maxk.push(happiness[i]);
}
// iterate while update
for (int i = k; i < happiness.size(); ++i) {
cur = happiness[i];
top = maxk.top();
// current elements smaller, just continue
if (cur <= top) {
continue;
}
// update elements
maxk.pop();
maxk.push(cur);
}
// at this point, all max-k elements are in the min heap
long long answer = 0;
int chooseTime, lost;
for (chooseTime = k - 1; chooseTime >= 0; --chooseTime) {
// get top element
cur = maxk.top();
maxk.pop();
if (debug) {
cout << "choosed: " << cur << endl;
}
// determine the lost of this element
lost = std::min({k, cur, chooseTime});
// update answer
answer += (cur - lost);
}
return answer;
}
};
```

View File

@@ -0,0 +1,347 @@
---
date: 2025-12-29
tags:
- Simulation
- "#Heap"
---
[Leetcode question link](https://leetcode.com/problems/meeting-rooms-iii)
# Analysis
Basically this is just an #Simulation problem.
> [!note]
>
> The most important time complexity optimization is to find out the **unused room management could exploit #Heap data structure**, checkout [[#Room Distribution Order]] for details
## Meeting Distribution Order
Since the `startTime` is promised to be unique, based on the rule, we know that the **distribution should goes from meetings with smaller `startTime` to larger one**. The basic thought is:
1. Sort `meetings`
2. Distribute `meeting` to room, counting usage statistics of each room
3. Output most used room
## Room Distribution Order
Based on the rules, we know that the room being distributed is **always the one with the smallest room number and currently available**. Conclude what operations we need for rooms.
| Operation | Descriptions |
| ---------------- | ----------------------------------------------------------------------------------------------- |
| `use()` | Mark a room used, that room should have the lowest `roomIdx` among all currently available room |
| `unuse(roomIdx)` | Unuse a room by it's index |
Here we introduce two approaches to achieve these.
### Array
We use an array `bool isUsed[N]` to record the status of a room. This require us to iterate the array to find out the lowest unused index, thus has time complexity $O(N)$
### Min Heap
We could find Minimum Heap suit this use case really well. We initial a min heap with all unused room index, and:
- `use()` Remove the index at the heap top
- `unuse()` Insert the index to the heap
By doing this, we could have $O(\log N)$ time complexity, considering $N$ is the number of room.
# Code Implementation
```cpp
#include <iostream>
#include <numeric>
#include <vector>
#include <format>
#include <algorithm>
#include <queue>
using std::cout, std::endl, std::format;
using std::vector, std::priority_queue;
const bool debug = false;
struct TaskInfo
{
unsigned start = 0;
unsigned end = 0;
TaskInfo(const vector<int> &vec) : start(vec[0]), end(vec[1]) {}
bool operator<(const TaskInfo &other)
{
if (start != other.start)
{
return start < other.start;
}
return end < other.end;
}
unsigned duration() const
{
return end - start;
}
void delay(unsigned delta)
{
start += delta;
end += delta;
}
void relocate(unsigned startTime)
{
end = startTime + duration();
start = startTime;
}
};
class MeetingRoomManager
{
private: // private member
vector<unsigned> mUseCount;
unsigned tmpMostUsedCount = 0;
std::priority_queue<unsigned, std::vector<unsigned>, std::greater<unsigned>> tmpUnusedIdxHeap;
public: // public member
// the count of the room
unsigned mCount = 0;
public: // public method
// initialize manager with room count
MeetingRoomManager(int count) : mCount(count)
{
mUseCount = vector<unsigned>(100);
clear(count);
}
/**
* Find a valid room, mark it as used and update the use count.
* Return index of the used room.
*
* Return 100 if room not found.
*/
unsigned use()
{
// room not found
if (tmpUnusedIdxHeap.empty())
{
return 100;
}
// found room with lowest index
unsigned unuse = tmpUnusedIdxHeap.top();
tmpUnusedIdxHeap.pop();
++mUseCount[unuse]; // update use count
// update most use if needed
if (mUseCount[unuse] > tmpMostUsedCount)
{
tmpMostUsedCount = mUseCount[unuse];
}
return unuse; // return room idx
}
/**
* Unuse a room by its index
*/
void unuse(unsigned roomIdx)
{
tmpUnusedIdxHeap.push(roomIdx);
}
unsigned mostUsedIdx()
{
for (int i = 0; i < mCount; ++i)
{
if (mUseCount[i] == tmpMostUsedCount)
{
return i;
}
}
return 0;
}
bool isFull()
{
return tmpUnusedIdxHeap.empty();
}
void clear(unsigned count)
{
// reset mCount
mCount = count;
// clear most use count
tmpMostUsedCount = 0;
// clear use count statistics
std::fill(mUseCount.begin(), mUseCount.end(), false);
// init unuse heap
tmpUnusedIdxHeap = std::priority_queue<unsigned, std::vector<unsigned>, std::greater<unsigned>>();
for (int i = 0; i < mCount; ++i)
{
tmpUnusedIdxHeap.push(i);
}
}
};
class RoomDistributor
{
private: // private classes
struct FutureReleaseInfo
{
unsigned time;
unsigned roomIdx;
bool operator<(const FutureReleaseInfo &other) const
{
if (time != other.time)
{
return time > other.time;
}
return roomIdx > other.roomIdx;
}
};
private: // private members
// manage room usage info
MeetingRoomManager mManager;
// record current timestamp
unsigned mCurTimestamp = 0;
// record when to release room
std::priority_queue<FutureReleaseInfo> mReleaseTimeHeap;
private: // private methods
// release one from heap
// will NOT check empty before action!
void releaseOne()
{
const FutureReleaseInfo &nextReleaseInfo = mReleaseTimeHeap.top();
mManager.unuse(nextReleaseInfo.roomIdx);
mCurTimestamp = std::max({nextReleaseInfo.time, mCurTimestamp});
mReleaseTimeHeap.pop();
}
// release all the room until the given timestamp
void pushTimeTo(unsigned targetTime)
{
// already pushed to a time later then given, nothing to do
if (mCurTimestamp > targetTime)
{
return;
}
// no room is used, just move the time
if (mReleaseTimeHeap.empty())
{
mCurTimestamp = targetTime;
return;
}
// release until target time
while (!mReleaseTimeHeap.empty() && mReleaseTimeHeap.top().time <= targetTime)
{
releaseOne();
}
mCurTimestamp = targetTime;
}
public:
RoomDistributor(unsigned roomCount) : mManager(roomCount) {}
// distribute a meeting task to the room
void distributeTask(const TaskInfo &taskInfo)
{
pushTimeTo(taskInfo.start);
// if room still full, push timestamp until next room release
if (mManager.isFull())
{
releaseOne();
}
// distribute a room
unsigned roomIdx = mManager.use();
// record a new future release
mReleaseTimeHeap.emplace(FutureReleaseInfo(mCurTimestamp + taskInfo.duration(), roomIdx));
}
/**
* Release all item that should be released in the future
*/
void releaseAll()
{
while (!mReleaseTimeHeap.empty())
{
releaseOne();
}
}
unsigned getMostUsedIdx()
{
return mManager.mostUsedIdx();
}
void clear(unsigned count)
{
// reset timestamp
mCurTimestamp = 0;
// clean heap
releaseAll();
// clear mManager
mManager.clear(count);
}
};
// global variables
unsigned roomCount, meetingCount;
RoomDistributor distributor(0);
vector<TaskInfo> tasks;
void initVariables(const vector<vector<int>> &meetings)
{
// init tasks
tasks.clear();
tasks.reserve(meetings.size());
for (const auto &m : meetings)
{
tasks.emplace_back(TaskInfo(m));
}
std::sort(tasks.begin(), tasks.end());
// init distributor
distributor.clear(roomCount);
}
void triggerSimulation()
{
for (const auto &t : tasks)
{
distributor.distributeTask(t);
}
distributor.releaseAll();
}
class Solution
{
public:
int mostBooked(int n, vector<vector<int>> &meetings)
{
roomCount = n;
meetingCount = meetings.size();
initVariables(meetings);
triggerSimulation();
return distributor.getMostUsedIdx();
}
};
```

View File

@@ -0,0 +1,75 @@
---
tags:
- Greedy
- Array
date: 2025-12-26
---
[Leetcode Question Link](https://leetcode.com/problems/minimum-penalty-for-a-shop)
# Analysis
## Offset
The target is to **find the time to achieve the smallest penalty, but not the penalty value itself**. So the concrete value of penalty is not important, we could just focus on **how penalty changes when changing shop closing time**.
Let `offset` be the penalty diff when choosing closing time $i$ and closing time $0$, that is:
$$
\text{offset}(i) = \text{penalty}(i) - \text{penalty}(0)
$$
## Moving Closing Time
Now let's find how $\text{offset}(i)$ changes when $i: 0 \to n$.
---
When $i = 0$, based on definition of offset, we have $\text{offset}(0) = 0$
-----
When we moving closing time $i$ from $k - 1$ to $k$, discuss:
**When at $k-1$ hour, there IS customers arriving.** In this case, before moving closing time, there is an $Y$ in closing time, after moving, the $Y$ has been moved into open time. So $\text{offset}$ actually decrease by $1$ after moving.
**When at $k-1$ hour, there IS NOT customers arriving.** by similar analysis method, we know there is an $N$ moved from closing time to opening time, $\text{offset}$ increase by $1$.
# Code Implementation
```cpp
class Solution {
public:
int bestClosingTime(string customers) {
// init offset
// at time 0, offset = 0
int offset = 0, minOffset = 0;
unsigned minTime = 0;
bool arrived;
int rangeEnd = customers.size() + 1;
for (int i = 1; i < rangeEnd; ++i) {
// check if there is customers arrived at previous time
arrived = (customers[i - 1] == 'Y' ? 1 : 0);
// someone arrived, then moving closing time
// 1 hour later will cause offset decreasing by 1,
// otherwise, offset increasing by 1
if (arrived)
--offset;
else
++offset;
// update minOffset and minTime
if (offset < minOffset) {
minOffset = offset;
minTime = i;
}
}
return minTime;
}
};
```

View File

@@ -0,0 +1,6 @@
---
title: Leetcode Questions
date: 2025-12-25
---
Some notes about Leetcode questions.