Merging Ore Piles
/*
Time limit: 5000ms
Memory limit: 256mb
---------------------Copy the following code, complete it and submit---------------------
I, <Your Full Name>, am submitting the assignment for
an individual project.
I declare that the assignment here submitted is original except for
source material explicitly acknowledged, the piece of work, or a part
of the piece of work has not been submitted for more than one purpose
(i.e. to satisfy the requirements in two different courses) without
declaration. I also acknowledge that I am aware of University policy
and regulations on honesty in academic work, and of the disciplinary
guidelines and procedures applicable to breaches of such policy and
regulations, as contained in the University website
http://www.cuhk.edu.hk/policy/academichonesty/.
It is also understood that assignments without a properly signed
declaration by the student concerned will not be graded by the
teacher(s).
*/
#include <stdio.h>
#include <stdlib.h>
/**
* Greedy strategy: always merge the two smallest files first.
*/
long long min_cost_merge(int *a, int n) {
// WRITE YOUR CODE HERE
}
// DO NOT MODIFY THE CODE BELOW
int main(void) {
int n;
if (scanf("%d", &n) != 1) return 0;
int *a = (int *)malloc((size_t)n * sizeof(int));
for (int i = 0; i < n; ++i) scanf("%d", &a[i]);
printf("%lld\n", min_cost_merge(a, n));
free(a);
return 0;
}
---------------------------------------End of Code---------------------------------------
## Merging Ore Piles
A mining company has $n$ piles of ore, each with a known weight. The company must merge all piles into a single pile by repeatedly combining two piles at a time. The **cost** of one merge equals the sum of the weights of the two piles being merged. The total cost is the sum of all individual merge costs.
Design an algorithm to find the **minimum total merging cost**.
**Key insight:** It can be proved that always merging the two lightest piles first yields the optimal solution. Think about what data structure allows you to efficiently achieve this.
### Input
- The first line contains an integer $n$ ($1 \leq n \leq 10^6$), the number of ore piles.
- The second line contains $n$ space-separated integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^5$), the weight of each pile.
### Output
A single integer — the minimum total merging cost. The answer may exceed $2^{31} - 1$; use a 64-bit integer type.
### Example
**Input**
```
5
1 2 3 4 5
```
**Output**
```
33
```
**Explanation**
Five piles with weights $1, 2, 3, 4, 5$. Always merge the two lightest piles first:
- Merge $1$ and $2$ → pile of weight $3$, cost $3$. Remaining: $\{3, 3, 4, 5\}$
- Merge $3$ and $3$ → pile of weight $6$, cost $6$. Remaining: $\{4, 5, 6\}$
- Merge $4$ and $5$ → pile of weight $9$, cost $9$. Remaining: $\{6, 9\}$
- Merge $6$ and $9$ → pile of weight $15$, cost $15$. Remaining: $\{15\}$
Total cost: $3 + 6 + 9 + 15 = \mathbf{33}$ (minimum possible).
Submit