标签:huffman har div alt ide gre class style return
##二分查找##
很久之前做过的Huffman编码,用优先队列
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<queue> 5 6 using namespace std; 7 8 const int lenth=300; 9 int main() 10 { 11 char str[10010]; 12 while(scanf("%s",str)) 13 { 14 if(strcmp(str,"END")==0) break; 15 int len=strlen(str); 16 int worse=len<<3;//固定长度编码所需的总位数 17 char ch[lenth]; 18 int lench=0;//输入字符的总类 19 int i,j,num[lenth];//对应每种字符的数目,无需关注具体对应哪个字符 20 memset(num,0,lenth); 21 22 for(i=0;i<len;i++) 23 { 24 for(j=0;j<lench;j++) //注意 25 if(str[i]==ch[j]) {num[j]++;break;} 26 if(j==lench) 27 { 28 ch[j]=str[i]; 29 num[j]++; 30 lench++; 31 } 32 } 33 34 priority_queue<int,vector<int>,greater<int> > pq; 35 for(int i=0;i<lench;i++) pq.push(num[i]); 36 int sum=0; 37 while(true) 38 { 39 int aa=pq.top(); 40 pq.pop(); 41 if(pq.empty()){ 42 if(lench==1) sum=aa; 43 break; 44 } 45 int bb=pq.top(); 46 pq.pop(); 47 sum+=aa+bb; 48 pq.push(aa+bb); 49 50 } 51 printf("%d %d %.1lf\n",worse,sum,worse*1.0/sum); 52 } 53 return 0; 54 }
好像又回到最开始只会看题解的时候了-_-||
1 #include<cstdio> 2 #include<iostream> 3 #include<sstream> 4 #include<algorithm> 5 using namespace std; 6 7 const int maxn=10005; 8 int a[maxn]; 9 int n; 10 11 void flip(int p){ 12 for(int i=0;i<p-i;i++) swap(a[i],a[p-i]); 13 14 printf("%d ",n-p); 15 } 16 17 18 19 int main(){ 20 string s; 21 while(getline(cin,s)){ 22 cout<<s<<"\n"; 23 stringstream ss(s) ; 24 n=0; 25 while(ss>>a[n]) n++; 26 27 for(int i=n-1;i>0;i--){ 28 int p=max_element(a,a+i+1)-a;//找到最大的数的下标 29 30 if(p==i) continue;//如果这块饼的位置是对的,就不管 31 if(p>0) flip(p);//如果饼不是在0位置,那么将这块饼 翻到0位置 32 flip(i);//将这块 饼翻到它应该在的位置 33 } 34 printf("0\n"); 35 } 36 return 0; 37 }
标签:huffman har div alt ide gre class style return
原文地址:http://www.cnblogs.com/yijiull/p/7158119.html