DS实验题 融合软泥怪-1
题目
思路
很容易想到第一种做法,用Huffman算法,从森林中找出两个值最小的节点,合并再加入森林,在这个过程中不断记录。
但是每一次需要sort一遍,将最小的两个值节点置于头两个节点,最坏情况下复杂度是O(n^3)的量级,结果是TLE。
第二种方法是利用STL中的priority_queue模板进行解题,很方便,这里给出AC代码。但是优先队列手写实现还是需要实践,将在下一篇进行实现。
代码
Huffman:
//
// main.cpp
// Huffman Tree2
//
// Created by wasdns on 16/12/24.
// Copyright © 2016年 wasdns. All rights reserved.
//
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
struct Node
{
int num;
Node *l, *r;
};
bool cmp(Node *n1, Node *n2)
{
if (n1 -> num != n2 -> num) return n1 -> num < n2 -> num;
return false;
}
Node *node[100005];
/*
Ininode:初始化节点
*/
void Ininode(int n)
{
int i;
for (i = 1; i <= n; i++)
{
node[i] = new Node;
cin >> node[i] -> num;
node[i] -> l = NULL;
node[i] -> r = NULL;
}
}
/*
Huffman函数
*/
int Huffman(int n)
{
int cnt = 0;
sort(node+1, node+n+1, cmp);
while (1)
{
if (node[2] -> num == 100005) //只剩下一棵树
{
break;
}
cnt += node[1] -> num;
cnt += node[2] -> num;
node[1] -> num = node[1] -> num + node[2] -> num; //1、2合并为1
node[2] -> num = 100005; //删除2
sort(node+1, node+n+1, cmp); //将值最小的两棵树前移
}
return cnt;
}
int main()
{
int n;
cin >> n;
Ininode(n);
int ans = Huffman(n);
cout << ans << endl;
return 0;
}
STL_Priority_Queue:
//
// main.cpp
// PriorityQueue STL
//
// Created by wasdns on 16/12/24.
// Copyright © 2016年 wasdns. All rights reserved.
//
#include <iostream>
#include <functional>
#include <queue>
using namespace std;
struct cmp
{
bool operator() (int x,int y) {
return x > y;
}
};
int storage[100005];
int main()
{
int n;
cin >> n;
//priority_queue<int, vector<int>, greater<int>> q;
priority_queue<int, vector<int>, cmp> q;
for (int i = 1; i <= n; i++)
{
cin >> storage[i];
q.push(storage[i]);
}
int cnt = 0;
while (q.size() > 1)
{
int x = q.top();
q.pop();
int y = q.top();
q.pop();
cnt += x+y;
q.push(x+y);
}
cout << cnt << endl;
return 0;
}
2016/12/24
To improve is to change, to be perfect is to change often.