Round #186 (Div.2) Ilya and Matrix

来源:互联网 发布:mysql 唯一约束语句 编辑:程序博客网 时间:2024/06/10 08:50
C. Ilya and Matrix
time limit per test
1 second
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 and4n integers. You need to arrange all these numbers in the matrix (put each number in a single individual cell) so that thebeauty 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 equalsm. Otherwise, a matrix can be split into 4 non-intersecting2n - 1 × 2n - 1-sized submatrices, then the beauty of the matrix equals the sum of numberm 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 contains4n integersai(1 ≤ ai ≤ 109) — the numbers you need to arrange in the2n × 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 thecin, cout streams or the%I64d specifier.

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个数,让你安排这个矩阵使得用上述递归算法得到的和最大。这个不要想复杂……其实在结果上来看,只要每次都取最大的放在左上角就可以得到最大和。因此对数组从大到小排序,每次都累加前四个值dfs一遍就行了。

代码如下:

/*ID: j.sure.1PROG: LANG: C++*//****************************************/#include <cstdio>#include <cstdlib>#include <cstring>#include <algorithm>#include <cmath>#include <stack>#include <queue>#include <vector>#include <map>#include <string>#include <iostream>using namespace std;/****************************************/#define LL long longconst int N = 2e6+10;int num[N];bool cmp(int a, int b){return a > b;}LL dfs(int deep, int cur){LL ans = 0;if(deep == 0)return num[cur];ans += num[cur];for(int i = 0; i < 4; i++) {ans += dfs(deep-1, cur*4+i);}return ans;}int main(){//freopen(".in", "r", stdin);//freopen(".out", "w", stdout);int n;scanf("%d", &n);for(int i = 0; i < n; i++) {scanf("%d", &num[i]);}sort(num, num+n, cmp);int deep = (int)log2(1.0*n)/2;printf("%I64d\n", dfs(deep, 0));return 0;}


0 0
原创粉丝点击