How does this loop work in C++? Is there an equivalent while loop?
int firstTrue(int lo, int hi, function<bool(int)> f) {
for (hi ++; lo < hi; ) {
int mid = lo+(hi-lo)/2;
if f(mid) hi = mid;
else lo = mid+1;
}
return lo;
}
| № | Пользователь | Рейтинг |
|---|---|---|
| 1 | Benq | 3792 |
| 2 | VivaciousAubergine | 3647 |
| 3 | Kevin114514 | 3603 |
| 4 | jiangly | 3583 |
| 5 | strapple | 3515 |
| 6 | tourist | 3470 |
| 7 | dXqwq | 3436 |
| 8 | Radewoosh | 3415 |
| 9 | Otomachi_Una | 3413 |
| 10 | Um_nik | 3376 |
| Страны | Города | Организации | Всё → |
| № | Пользователь | Вклад |
|---|---|---|
| 1 | Qingyu | 157 |
| 2 | adamant | 153 |
| 3 | Um_nik | 146 |
| 3 | Proof_by_QED | 146 |
| 5 | Dominater069 | 145 |
| 6 | errorgorn | 141 |
| 7 | cry | 139 |
| 8 | YuukiS | 135 |
| 9 | TheScrasse | 134 |
| 10 | chromate00 | 133 |
How does this loop work in C++? Is there an equivalent while loop?
int firstTrue(int lo, int hi, function<bool(int)> f) {
for (hi ++; lo < hi; ) {
int mid = lo+(hi-lo)/2;
if f(mid) hi = mid;
else lo = mid+1;
}
return lo;
}
| Название |
|---|



I don't understand what you're trying to ask.
The loop you have is an infinite loop if
hi >= lo, so the equivalent while loop iswhile (true) {}.Please elaborate on what you want the loop to do
It is just a simple binary search. This is an equivalent code:
(Sorry spoilers are broken)
This is a binary search. I dislike the way that r is incremented in the beggining of the function, so I removed it. This will only work if there exists an index $$$x$$$ such that for all $$$l \leqslant i \lt x$$$, $$$f(i) = 0$$$ and for all $$$x \leqslant i \lt r$$$, $$$f(i) = 1$$$. We want to find $$$x$$$. We will keep an invariant, that $$$l \leqslant x \leqslant r$$$. Let $$$m = (l + r)/2$$$. If $$$f(m) = 1$$$, it means that $$$x \leqslant m$$$, thus, the invariant still holds after the operation $$$r = m$$$. Otherwise, $$$f(m) = 0$$$, which means that $$$x$$$ is strictly greater than $$$l$$$, thus, after the operation $$$l = m + 1$$$, the invariant still holds. Notice that after each turn $$$r - l$$$ will decrease in at least one, which implies that it won't get stuck in an infinite loop. This method is called binary search because it takes logarithm time to compute $$$x$$$. You can read more about complexity online.
EDIT: Added detailed explanation
can you please explain function<bool (int)> f)
what is this and why is it needed over here?