UVA - 10954
Description Problem F Yup!! The problem name reflects your task; just add a set of numbers. But you may feel yourselves condescended, to write a C/C++ program just to add a set of numbers. Such a problem will 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 two to be added. So, to add 1 and 10, you need a cost of 11. If you want to add 1, 2 and 3. There are several ways –
I hope you have understood already your mission, to add a set of integers so that the cost is minimal.
InputEach test case will start with a positive number, N (2 ≤ N ≤ 5000) followed by N positive integers (all are less than 100000). Input is terminated by a case where the value of N is zero. This case should not be processed.
OutputFor each case print the minimum total cost of addition in a single line.
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 Structures 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 :: Examples |
思路:每次加两个最小的,然后将两个最小的删去,将和插入到剩余的数中,直到只剩一个数
AC代码:
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <cmath> #define LL long long using 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]); printf("%lld\n", ans); } return 0; }
原文地址:http://blog.csdn.net/u014355480/article/details/44786911