POJ - 1862:Stripies

Stripies

来源:POJ

标签:贪心算法,优先队列

参考资料:

相似题目:

题目

Our chemical biologists have invented a new very useful form of life called stripies (in fact, they were first called in Russian - polosatiki, but the scientists had to invent an English name to apply for an international patent). The stripies are transparent amorphous amebiform creatures that live in flat colonies in a jelly-like nutrient medium. Most of the time the stripies are moving. When two of them collide a new stripie appears instead of them. Long observations made by our scientists enabled them to establish that the weight of the new stripie isn’t equal to the sum of weights of two disappeared stripies that collided; nevertheless, they soon learned that when two stripies of weights m1 and m2 collide the weight of resulting stripie equals to 2sqrt(m1m2). Our chemical biologists are very anxious to know to what limits can decrease the total weight of a given colony of stripies.
You are to write a program that will help them to answer this question. You may assume that 3 or more stipies never collide together.

输入

The first line of the input contains one integer N (1 <= N <= 100) - the number of stripies in a colony. Each of next N lines contains one integer ranging from 1 to 10000 - the weight of the corresponding stripie.

输出

The output must contain one line with the minimal possible total weight of colony with the accuracy of three decimal digits after the point.

输入样例

3
72
30
50

输出样例

120.000

样例解释

首先,72和50碰撞得到120,120再和30碰撞得到120。

题目大意

在一组数中,任两个数a和b可以结合生成一个新数,结合方法是 2 ∗ a ∗ b 2*\sqrt{a*b} 2ab ,试求这些数经过有限次的结合,最终得到的最小的数。

解题思路

对于三个数 a 3 > a 2 > a 1 > 0 a_{3}>a_{2}>a_{1}>0 a3>a2>a1>0,很容易推导出 a 3 a 2 ∗ a 1 < a 1 a 3 ∗ a 2 < a 1 a 2 ∗ a 3 \sqrt{\sqrt{a_{3}a_{2}}*a_{1}}<\sqrt{\sqrt{a_{1}a_{3}}*a_{2}}<\sqrt{\sqrt{a_{1}a_{2}}*a_{3}} a3a2 a1 <a1a3 a2 <a1a2 a3 (两次平方)。贪心算法策略,每次从集合中选出最大的两个数计算结果,再将结果放进集合中,利用优先队列来实现。

参考代码

#include
#include
#include
using namespace std;

priority_queue<double> pq;
int N;

int main(){
	scanf("%d",&N);
	while(N--){
		int w;
		scanf("%d", &w);
		pq.push(w);
	}
	while(pq.size()>1){
		double a=pq.top(); pq.pop();
		double b=pq.top(); pq.pop();
		pq.push(2*sqrt(a*b));
	}
	printf("%.3f\n", pq.top());
	return 0;
}

你可能感兴趣的:(【记录】算法题解)