// 演算法：把小行星由小到大排序，依序碰撞。/ Algorithm: sort asteroids ascending, collide in order.
// 每次都吃最小的，行星越長越重；若連最小的剩餘小行星都撞不過就失敗。
// Always eat the smallest first so the planet grows; if even that fails, return false.

// qsort 需要的比較函式：回傳負/零/正代表 a 排在 b 前/相等/後。
// Comparator for qsort: return negative/zero/positive means a goes before/equal/after b.
int cmp(const void *a, const void *b) {
    // *(const int *)a 是把 void 指標轉回 int 指標再取值 / cast void* back to int* then dereference.
    int x = *(const int *)a;
    int y = *(const int *)b;
    // 用相減可能溢位，所以用比較式回傳 -1/0/1 比較安全。
    // Subtraction could overflow, so compare and return -1/0/1 instead.
    return (x > y) - (x < y);
}

bool asteroidsDestroyed(int mass, int* asteroids, int asteroidsSize) {
    // 原地把陣列由小到大排序 / sort the array ascending in place.
    // 參數：起始位址、元素個數、每個元素的位元組大小、比較函式。
    // Args: start address, element count, size of each element, comparator.
    qsort(asteroids, asteroidsSize, sizeof(int), cmp);

    // cur 用 long long（64 位元）避免溢位，初始為行星質量。
    // cur is long long (64-bit) to avoid overflow; starts as the planet's mass.
    long long cur = mass;

    // 從最小的小行星開始一顆一顆撞 / loop through asteroids smallest first.
    for (int i = 0; i < asteroidsSize; i++) {
        // 若現在質量小於這顆小行星，行星被毀，無法全部摧毀。
        // If current mass is smaller than this asteroid, the planet dies → cannot destroy all.
        if (cur < asteroids[i]) {
            return false;
        }
        // 否則摧毀它並吸收其質量 / otherwise destroy it and absorb its mass.
        cur += asteroids[i];
    }

    // 全部撞完都沒失敗，代表可以摧毀所有小行星。
    // Got through all without failing → every asteroid can be destroyed.
    return true;
}
