Codeforce 313C Ilya and Matrix

来源:互联网 发布:淘宝电子面单怎么关联 编辑:程序博客网 时间:2024/05/17 09:38
C. Ilya and Matrix
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Ilya is a very good-natured lion. He likes maths. Of all mathematical objects, his favourite one is matrices. Now he's faced a complicated matrix problem he needs to solve.

He's got a square 2n × 2n-sized matrix and 4n integers. You need to arrange all these numbers in the matrix (put each number in a single individual cell) so that the beauty of the resulting matrix with numbers is maximum.

The beauty of a 2n × 2n-sized matrix is an integer, obtained by the following algorithm:

  1. Find the maximum element in the matrix. Let's denote it as m.
  2. If n = 0, then the beauty of the matrix equals m. Otherwise, a matrix can be split into 4 non-intersecting 2n - 1 × 2n - 1-sized submatrices, then the beauty of the matrix equals the sum of number m and other four beauties of the described submatrices.

As you can see, the algorithm is recursive.

Help Ilya, solve the problem and print the resulting maximum beauty of the matrix.

Input

The first line contains integer 4n (1 ≤ 4n ≤ 2·106). The next line contains 4n integers ai (1 ≤ ai ≤ 109) — the numbers you need to arrange in the 2n × 2n-sized matrix.

Output

On a single line print the maximum value of the beauty of the described matrix.

Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cincout streams or the %I64dspecifier.

Sample test(s)
input
113
output
13
input
41 2 3 4
output
14
Note

Consider the second sample. You need to arrange the numbers in the matrix as follows:

1 23 4

Then the beauty of the matrix will equal: 4 + 1 + 2 + 3 + 4 = 14.

题意:给你4^n个数,让你放在一个2^nX2^n的矩阵中,使得安排后的和最大。

往矩阵里填数的原则是:

1、找出这如果4^n个数中最大的数,记为m,sum+=m;

2、当n=0,即矩阵中只有一个数时,这个数就是m;否则,把这个矩阵分成4个2^n-1X2^n-1的子矩阵,重复上面的操作,直到每个子矩阵中只有一个数为止。

解题思路:因为题目要求得到的和最大,所以每次执行sum+=m时,都尽量使m最大,于是我们就可以先把这4^n个数从大到小排一下序,然后从大到小依次填入每个矩阵中。这样加的时候,让sum第一次加上第一大,第二次加上前4大,第三次加上前16大,……这样就能保证得到的和是最大的。

#include<stdio.h>#include<math.h>#include<algorithm>using namespace std;bool comp(int a,int b)//从大到小排序{return a>b;}int a[2000002];int main(){__int64 n,sum,i,k;while(~scanf("%I64d",&n)){for(i=0;i<n;i++)scanf("%I64d",&a[i]);sort(a,a+n,comp);k=1;sum=0;while(k<=n){   for(i=0;i<k;i++)//每次加上前4的i次方大  sum+=a[i];   k*=4; //4的次方}printf("%I64d\n",sum);}return 0;}