@moytrage/

RuStackOverflow_734585

C

No description

fork
loading
Files
  • main.c
main.c
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <stdio.h>
#include <stdint.h>

typedef uint64_t u64;

u64 const c_peak = 11241155978086311589ULL;
u64 const c_cnt = 13356955260197607378ULL;

u64 peak(u64 nel, int(*less)(u64 i, u64 j))
{
    if (nel <= 1) return 0; // Note: if nel == 0 there is no answer!
    if (!less(0, 1)) return 0;
    if (!less(nel - 1, nel - 2)) return nel - 1;
    
    u64 l = 1, r = nel - 1;
    while (r - l > 2) {
        u64 m = l + (r - l) / 2;
        if (less(m + 1, m)) r = m + 1; else l = m;
    }
    if (r - l == 2 && !less(l, l + 1) || r - l <= 1) return l; else return l + 1;
}

int less(u64 i, u64 j)
{
    if (i == j) return 0;

    if (i < j) {
        if (j <= c_peak) return 1;
        if (i >= c_peak) return 0;
        return (c_peak - i) < (j - c_peak);
    } else {
        if (i <= c_peak) return 0;
        if (j >= c_peak) return 1;
        return (c_peak - j) < (i - c_peak);
    }
}

u64 peak(u64, int (*)(u64, u64));

int main(int argc, char **argv)
{
    u64 i = peak(c_cnt, less);
    if (i == c_peak) {
        printf("CORRECT\n");
    } else { 
        printf("WRONG\n");
    }
    return 0;
}