poj3253 Fence Repair(贪心+哈夫曼 经典)

https://vjudge.net/problem/POJ-3253

很经典的题,运用哈夫曼思想,想想很有道理!!

具体实现还是有点绕人,最后被long long卡了一下,看数据大小的时候单纯相乘了。。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<queue>
 4 #include<cstring>
 5 #include<algorithm>
 6 #include<cmath>
 7 #include<set>
 8 #define INF 0x3f3f3f3f
 9 typedef long long ll;
10 using namespace std;
11 int n, L[100010];
12 ll ans=0;
13 int main()
14 {
15     cin >> n;
16     for(int i = 0; i < n; i++){
17         cin >> L[i];
18     }
19     sort(L, L+n);
20     while(n > 1){
21         int mii1 = 0, mii2 = 1;//mii1指向最小,mii2指向次小 
22         if(L[mii1] > L[mii2]){//保证L[mii1]<L[mii2] 
23             swap(L[mii1], L[mii2]);
24         } 
25         for(int i = 2; i < n; i++){//循环中的操作都是基于L[mii1]<L[mii2]指向 
26             if(L[i] < L[mii1]){
27                 mii2 = mii1;
28                 mii1 = i;
29             } 
30             else if(L[i] < L[mii2]){
31                 mii2 = i;
32             }
33         }
34         int t = L[mii1] + L[mii2]; 
35         ans += t;
36         if(mii1 == n-1){//防止这个位置和最后一个位置重叠 
37             swap(L[mii1], L[mii2]);
38         }
39         L[mii1] = t; 
40         L[mii2] = L[n-1];//把最后的一个移到mii2位置上,最后一个为空 
41         n--;
42     }
43     cout << ans << endl;
44     return 0;
45 }
原文地址:https://www.cnblogs.com/Surprisezang/p/9005969.html