POJ 3253 Fence Repair (哈夫曼编码基础)

POJ 3253


用了哈夫曼编码的思想

参考博客:http://blog.csdn.net/lyy289065406/article/details/6647423


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
long long L[20010];
int main() {
    int n;
    while(~scanf("%d", &n)) {
    	int i, j;
    	for(i = 0 ; i < n; i++) {
    		scanf("%I64d", L + i);
		}
		sort(L, L + n);
		long long minn = 0, sum;
		for(i = 0; i < n - 1; i++) { //n - 1 次后就剩下一根木棍了,此时停止
			sum = L[i] + L[i + 1];
			minn += sum;
			for(j = i + 2; j < n; j++) {
				if(sum > L[j]) {
					L[j - 1] = L[j];  //向后移动
					if(j == n - 1) {  //到了最后一根时放最后
						L[j] = sum;
					}
				}
				else {
					L[j - 1] = sum; //找到位置
					break;
				}
			}
		}
		printf("%I64d\n", minn);
	}
    return 0;
}


你可能感兴趣的:(POJ 3253 Fence Repair (哈夫曼编码基础))