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

时间:2023-03-09 01:14:34
poj3253 Fence Repair(贪心+哈夫曼 经典)

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

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

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

 #include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<set>
#define INF 0x3f3f3f3f
typedef long long ll;
using namespace std;
int n, L[];
ll ans=;
int main()
{
cin >> n;
for(int i = ; i < n; i++){
cin >> L[i];
}
sort(L, L+n);
while(n > ){
int mii1 = , mii2 = ;//mii1指向最小,mii2指向次小
if(L[mii1] > L[mii2]){//保证L[mii1]<L[mii2]
swap(L[mii1], L[mii2]);
}
for(int i = ; i < n; i++){//循环中的操作都是基于L[mii1]<L[mii2]指向
if(L[i] < L[mii1]){
mii2 = mii1;
mii1 = i;
}
else if(L[i] < L[mii2]){
mii2 = i;
}
}
int t = L[mii1] + L[mii2];
ans += t;
if(mii1 == n-){//防止这个位置和最后一个位置重叠
swap(L[mii1], L[mii2]);
}
L[mii1] = t;
L[mii2] = L[n-];//把最后的一个移到mii2位置上,最后一个为空
n--;
}
cout << ans << endl;
return ;
}