1. 程式人生 > >基礎練習--huffman

基礎練習--huffman

ron brush node 代碼 ios struct color body highlight

問題描述
  Huffman樹在編碼中有著廣泛的應用。在這裏,我們只關心Huffman樹的構造過程。
  給出一列數{pi}={p0, p1, …, pn-1},用這列數構造Huffman樹的過程如下:
  1. 找到{pi}中最小的兩個數,設為pa和pb,將pa和pb從{pi}中刪除掉,然後將它們的和加入到{pi}中。這個過程的費用記為pa + pb。
  2. 重復步驟1,直到{pi}中只剩下一個數。
  在上面的操作過程中,把所有的費用相加,就得到了構造Huffman樹的總費用。
  本題任務:對於給定的一個數列,現在請你求出用該數列構造Huffman樹的總費用。

  例如,對於數列{pi}
={5, 3, 8, 2, 9},Huffman樹的構造過程如下:   1. 找到{5, 3, 8, 2, 9}中最小的兩個數,分別是2和3,從{pi}中刪除它們並將和5加入,得到{5, 8, 9, 5},費用為5。   2. 找到{5, 8, 9, 5}中最小的兩個數,分別是5和5,從{pi}中刪除它們並將和10加入,得到{8, 9, 10},費用為10。   3. 找到{8, 9, 10}中最小的兩個數,分別是8和9,從{pi}中刪除它們並將和17加入,得到{10, 17},費用為17。   4. 找到{10, 17}中最小的兩個數,分別是10和17,從{pi}中刪除它們並將和27加入,得到{27},費用為27。   
5. 現在,數列中只剩下一個數27,構造過程結束,總費用為5+10+17+27=59。 輸入格式   輸入的第一行包含一個正整數n(n<=100)。   接下來是n個正整數,表示p0, p1, …, pn-1,每個數不超過1000。 輸出格式   輸出用這些數構造Huffman樹的總費用。 樣例輸入 5 5 3 8 2 9 樣例輸出 59
這個代碼超時  超時的點應該是每一次就只是簡單的加一個元素,循環時候還要
循環他
改進的辦法是進行刪除的操作

1
#include <iostream> 2 using namespace std; 3 int n; 4 struct node{
5 int date; 6 int flag; 7 }; 8 struct node a[200]; 9 int min() 10 { 11 int m=9999; 12 int k; 13 for(int i=0;i<n;i++) 14 { 15 if(a[i].date<m&&a[i].flag==0) 16 { 17 m=a[i].date; 18 k=i; 19 } 20 } 21 a[k].flag=1; 22 return k; 23 } 24 void add(int l) 25 { 26 a[n].flag =0; 27 a[n].date=l; 28 n++; 29 /* for(int x=0;x<n;x++) 30 { 31 cout<<"date"<<a[x].date<<" "; 32 cout<<"flag"<<a[x].flag<<endl; 33 34 }*/ 35 } 36 int is() 37 { int t=0; 38 for(int k=0;k<n;k++) 39 { 40 if(a[k].flag==0) 41 { 42 t++; 43 } 44 } 45 if(t==1) 46 { 47 return t; 48 } 49 if(t>1) 50 { 51 return 0; 52 } 53 } 54 int main() 55 { 56 int sum=0; 57 int s=0; 58 int fron; 59 int after; 60 int o; 61 cin>>n; 62 for(int i=0;i<n;i++) 63 { 64 cin>>a[i].date; 65 } 66 while(1){ 67 fron=a[min()].date;//找一個最小的 68 after=a[min()].date;//再找一個 最小的 69 s=fron+after; 70 //cout<<sum<<endl; 71 add(s); 72 sum=sum+s; 73 int t=is();//如果還剩下一個數 返回一個1 74 if(t) 75 { 76 break; 77 sum=sum+t; 78 } 79 } 80 cout<<sum; 81 return 0; 82 }
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
int n;
int a[200];
bool complare(int a,int b)
{
 return a>b;
}
void min()
{
  sort(a,a+n,complare);
  /*	for(int x=0;x<n;x++)
	{
		cout<<"date"<<a[x]<<" ";	
	}*/
}
/*void add(int l)
{
	a[n].flag =0;
	a[n].date=l;
	n++;
/**/
    

int main()
{
   int sum=0;
   int s=0;
   int fron;
   int after;
   int o;
   cin>>n;
   for(int i=0;i<n;i++)
   {
   	cin>>a[i];
   }
   while(n>1){
   	min(); 
	
   a[n-2]=a[n-1]+a[n-2]; 
   //cout<<"a[n-2]"<<a[n-2] <<endl;
   sum=sum+a[n-2];
   n--;
   } 
   cout<<sum;
	return 0;
}

  

基礎練習--huffman