基础训练 Huffuman树

Huffuman树

/*解法一*/
#include<iostream>
#include<queue>
using namespace std;
int main(){
	priority_queue< int, vector<int>, greater<int> > q;
	int n, t, sum = 0;
	cin>>n;
	for( int i=0; i<n; i++ ) {
		cin>>t;
		q.push( t );
	}
	while( q.size() != 1 ){
		int a = q.top();
		q.pop();
		int b = q.top();
		q.pop();
		int c = a + b;
		sum += c;
		q.push( c );
	}
 	cout<<sum<<endl;
 	return 0;
} 
/*解法二*/
#include<iostream>
#include<set>
using namespace std;
int main(){
	multiset<int> s;
	int n, t, sum = 0;
	cin>>n;
	for( int i = 0; i < n; i++ ) {
		cin>>t;
		s.insert(t);
	}
	while( s.size() != 1 ) {
		int a = *( s.begin() );
		s.erase( s.begin() );
		int b = *( s.begin() );
		s.erase( s.begin() );
		int c = a + b;
		sum += c;
		s.insert(c);
	}
	cout<<sum<<endl;
	return 0;
}
posted @ 2019-01-29 20:41  A-Little-Nut  阅读(106)  评论(0编辑  收藏  举报