//
// Created by gint on 2025/7/7.
//
#include <stdlib.h>

int cmpEvent(const void *a, const void *b)
{
    int *eventA = *(int **)a;
    int *eventB = *(int **)b;
    return eventA[0] - eventB[0];
}

int compare(const void *a, const void *b)
{
    return *(int *)a - *(int *)b;
}

// 简易小根堆操作
void push(int *heap, int *size, int val)
{
    int i = (*size)++;
    heap[i] = val;
    while (i > 0 && heap[(i - 1) / 2] > heap[i])
    {
        int tmp = heap[i];
        heap[i] = heap[(i - 1) / 2];
        heap[(i - 1) / 2] = tmp;
        i = (i - 1) / 2;
    }
}

int pop(int *heap, int *size)
{
    int result = heap[0];
    heap[0] = heap[--(*size)];
    int i = 0;
    while (i * 2 + 1 < *size)
    {
        int j = i * 2 + 1;
        if (j + 1 < *size && heap[j + 1] < heap[j])
            j++;
        if (heap[i] <= heap[j])
            break;
        int tmp = heap[i];
        heap[i] = heap[j];
        heap[j] = tmp;
        i = j;
    }
    return result;
}

int maxEvents(int **events, int eventsSize, int *eventsColSize)
{
    qsort(events, eventsSize, sizeof(int *), cmpEvent);

    int minDay = events[0][0], maxDay = 0;
    for (int i = 0; i < eventsSize; i++)
    {
        if (events[i][1] > maxDay)
            maxDay = events[i][1];
    }

    int heap[eventsSize];
    int heapSize = 0;

    int day = minDay, idx = 0, res = 0;

    for (day = minDay; day <= maxDay; day++)
    {
        // 把今天开始的会议加进堆
        while (idx < eventsSize && events[idx][0] == day)
        {
            push(heap, &heapSize, events[idx][1]);
            idx++;
        }

        // 去掉已过期的会议
        while (heapSize > 0 && heap[0] < day)
        {
            pop(heap, &heapSize);
        }

        // 选择今天可以开的最早结束的会议
        if (heapSize > 0)
        {
            pop(heap, &heapSize);
            res++;
        }
    }
    return res;
}
