UVA-10954ADD All
Time Limit: 3000MS |
Memory Limit: Unknown |
64bit IO Format: %lld &%llu |
Submit Status Description Problem F ADD All Input: standard input output: standard output
yup!! The problem name reflects your task; Just add a set of numbers. But the feel yourselves condescended, to write a C + + program just to add a set of numbers. Such a problem would simply question your erudition. So, let's add some flavor of ingenuity to it. Addition operation requires cost now, and the cost is the summation of those, and the was added. So, to add 1 and ten, you need a cost of one. If you want to add 1, 2 and 3. There is several ways–
1 + 2 = 3, cost = 3 3 + 3 = 6, cost = 6 Total = 9 |
1 + 3 = 4, cost = 4 2 + 4 = 6, cost = 6 Total = 10 |
2 + 3 = 5, cost = 5 1 + 5 = 6, cost = 6 Total = 11 |
I Hope you has understood already your mission, to add a set of integers so that's the cost is minimal. InputEach test case would start with a positive number, N (2≤n≤5000) followed by N positive integers (all is less than 100000). Input is terminated by a case where the value of N is zero. This case is should not being processed. OutputFor each case, print the minimum total cost of addition Sample input Output for sample input
Problem setter:md. Kamruzzaman, EPS Source Root:: AOAPC i:beginning algorithm Contests (Rujia Liu):: Volume 4. Algorithm Design Root:: Competitive programming 2:this increases the lower bound of programming contests. Again (Steven & Felix Halim):: Data Structures and Libraries:: Non Linear Data structures with built-in Libraries:: C + + STL priority_queue (Java priorityqueue) Root:: Prominent problemsetters:: Md. Kamruzzaman (Kzaman) Root:: Competitive programming 3:the New Lower Bound of programming contests (Steven & Felix Halim):: Data Structur Es and Libraries:: Non Linear Data structures with built-in Libraries:: C + + STL priority_queue (Java priorityqueue) Root:: AOAPC ii:beginning algorithm Contests (Second Edition) (Rujia Liu):: Chapter 8. Algorithm Design:: ExamplesSubmit Status |
|
Idea: Add two minimum each time, then delete the two smallest, and insert it into the remaining number until only one number is left.
AC Code:
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include < Cmath> #define LL Long longusing namespace Std;int N; LL A[5005];int Main () {while (scanf ("%d", &n), N) {for (int i = 0; i < N; i++) {scanf ("%lld", &a[i]);} Sort (A, a + N); ll ans = 0;for (int i = 0; i < N-1; i++) {LL tmp = a[i + 1] + A[i];ans + = tmp;a[i + 1] = tmp;if (i < N-2) {int t = i + 2;while (t <= N-1 && a[t] < TMP) {a[t-1] = a[t];a[t] = tmp;t++;}}} for (int i = 0; i < N; i++) printf ("%d", A[i]);p rintf ("%lld\n", ans);} return 0;}
Uva-10954-add All (greedy)