点击打开题目链接 poj3253
| Time Limit: 2000MS | Memory Limit: 65536K | |
| Total Submissions: 25986 | Accepted: 8382 |
Description
Farmer John wants to repair a small length of the fence around the pasture. He measures the fence and finds that he needs N (1 ≤ N ≤ 20,000) planks of wood, each having some integer length Li (1 ≤ Li ≤ 50,000) units. He then purchases a single long board just long enough to saw into the N planks (i.e., whose length is the sum of the lengths Li). FJ is ignoring the "kerf", the extra length lost to sawdust when a sawcut is made; you should ignore it, too.
FJ sadly realizes that he doesn't own a saw with which to cut the wood, so he mosies over to Farmer Don's Farm with this long board and politely asks if he may borrow a saw.
Farmer Don, a closet capitalist, doesn't lend FJ a saw but instead offers to charge Farmer John for each of the N-1 cuts in the plank. The charge to cut a piece of wood is exactly equal to its length. Cutting a plank of length 21 costs 21 cents.
Farmer Don then lets Farmer John decide the order and locations to cut the plank. Help Farmer John determine the minimum amount of money he can spend to create the N planks. FJ knows that he can cut the board in various different orders which will result in different charges since the resulting intermediate planks are of different lengths.
Input
Lines 2.. N+1: Each line contains a single integer describing the length of a needed plank
Output
Sample Input
3 8 5 8
Sample Output
34
Hint
The original board measures 8+5+8=21. The first cut will cost 21, and should be used to cut the board into pieces measuring 13 and 8. The second cut will cost 13, and should be used to cut the 13 into 8 and 5. This would cost 21+13=34. If the 21 was cut into 16 and 5 instead, the second cut would cost 16 for a total of 37 (which is more than 34).
题解:来自:http://blog.youkuaiyun.com/lyy289065406/article/details/6647423
大致题意:
有一个农夫要把一个木板钜成几块给定长度的小木板,每次锯都要收取一定费用,这个费用就是当前锯的这个木版的长度
给定各个要求的小木板的长度,及小木板的个数n,求最小费用
提示:
以
3
5 8 5为例:
先从无限长的木板上锯下长度为 21 的木板,花费 21
再从长度为21的木板上锯下长度为5的木板,花费5
再从长度为16的木板上锯下长度为8的木板,花费8
总花费 = 21+5+8 =34
解题思路:
利用Huffman思想,要使总费用最小,那么每次只选取最小长度的两块木板相加,再把这些“和”累加到总费用中即可
本题虽然利用了Huffman思想,但是直接用HuffmanTree做会超时,可以用优先队列做
因为朴素的HuffmanTree思想是:
(1)先把输入的所有元素升序排序,再选取最小的两个元素,把他们的和值累加到总费用
(2)把这两个最小元素出队,他们的和值入队,重新排列所有元素,重复(1),直至队列中元素个数<=1,则累计的费用就是最小费用
HuffmanTree超时的原因是每次都要重新排序,极度浪费时间,即使是用快排。
一个优化的处理是:
(1)只在输入全部数据后,进行一次升序排序 (以后不再排序)
(2)队列指针p指向队列第1个元素,然后取出队首的前2个元素,把他们的和值累计到总费用,再把和值sum作为一个新元素插入到队列适当的位置
由于原队首的前2个元素已被取出,因此这两个位置被废弃,我们可以在插入操作时,利用后一个元素位置,先把队列指针p+1,使他指向第2个废弃元素的位置,然后把sum从第3个位置开始向后逐一与各个元素比较,若大于该元素,则该元素前移一位,否则sum插入当前正在比较元素(队列中大于等于sum的第一个元素)的前一个位置
(3)以当前p的位置作为新队列的队首,重复上述操作
另一种处理方法是利用STL的优先队列,priority_queue,非常方便简单高效,虽然priority_queue的基本理论思想还是上述的优化思想,但是STL可以直接用相关的功能函数实现这些操作,相对简单,详细参见我的程序。
注意priority_queue与qsort的比较规则的返回值的意义刚好相反
AC code:
#include <iostream>
#include <queue>
#include <cstring>
#include <cstdio>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
priority_queue<int,vector<int>,greater<int> > qu;
for(int i=1; i<=n; i++)
{
int x;
cin>>x;
qu.push(x);
}
__int64 res =0,a=0,b=0;
while(true)
{
a = qu.top();
qu.pop();
if(qu.empty())
{
break;
}
b = qu.top();
qu.pop();
res+=a+b;
qu.push(a+b);
}
printf("%I64d\n",res);
}
return 0;
}
点击打开题目链接ZOJ 2339
You might have heard about Huffman encoding - that is the coding system that minimizes the expected length of the text if the codes for characters are required to consist of an integral number of bits.
Let us recall codes assignment process in Huffman encoding. First the Huffman tree is constructed. Let the alphabet consist of N characters, i-th of which occurs Pi times in the input text. Initially all characters are considered to be active nodes of the future tree, i-th being marked with Pi. On each step take two active nodes with smallest marks, create the new node, mark it with the sum of the considered nodes and make them the children of the new node. Then remove the two nodes that now have parent from the set of active nodes and make the new node active. This process is repeated until only one active node exists, it is made the root of the tree.
Note that the characters of the alphabet are represented by the leaves of the tree. For each leaf node the length of its code in the Huffman encoding is the length of the path from the root to the node. The code itself can be constrcuted the following way: for each internal node consider two edges from it to its children. Assign 0 to one of them and 1 to another. The code of the character is then the sequence of 0s and 1s passed on the way from the root to the leaf node representing this character.
In this problem you are asked to detect the length of the text after it being encoded with Huffman method. Since the length of the code for the character depends only on the number of occurences of this character, the text itself is not given - only the number of occurences of each character. Characters are given from most rare to most frequent.
Note that the alphabet used for the text is quite huge - it may contain up to 500 000 characters.
This problem contains multiple test cases!
The first line of a multiple input is an integer N, then a blank line followed by N input blocks. Each input block is in the format indicated in the problem description. There is a blank line between input blocks.
The output format consists of N output blocks. There is a blank line between output blocks.
Input
The first line of the input file contains N - the number of different characters used in the text (2 <= N <= 500 000). The second line contains N integer numbers Pi - the number of occurences of each character (1 <= Pi <= 109, Pi <= Pi+1 for all valid i).
Output
Output the length of the text after encoding it using Huffman method, in bits.
Sample Input
1
3
1 1 4
Sample Output
8
#include <iostream>
#include <queue>
#include <cstdio>
using namespace std;
int main()
{
int mcase;
scanf("%d",&mcase);
while(mcase--)
{
int n;
priority_queue<long long,vector<long long>,greater<long long> > qu;
scanf("%d",&n);
for(int i=1; i<=n; i++)
{
long long x;
cin>>x;
qu.push(x);
}
long long a=0,b=0;
long long res = 0;
while(true)
{
a = qu.top();
qu.pop();
if(qu.empty())
break;
b = qu.top();
qu.pop();
res += a+b;
qu.push(a+b);
}
cout<<res<<endl;
if(mcase!=0)
cout<<endl;
}
return 0;
}
点击打开点解poj1521 hdu1053 zoj1117
| Time Limit: 1000MS | Memory Limit: 10000K | |
| Total Submissions: 4891 | Accepted: 1909 |
Description
English text encoded in ASCII has a high degree of entropy because all characters are encoded using the same number of bits, eight. It is a known fact that the letters E, L, N, R, S and T occur at a considerably higher frequency than do most other letters in english text. If a way could be found to encode just these letters with four bits, then the new encoding would be smaller, would contain all the original information, and would have less entropy. ASCII uses a fixed number of bits for a reason, however: it’s easy, since one is always dealing with a fixed number of bits to represent each possible glyph or character. How would an encoding scheme that used four bits for the above letters be able to distinguish between the four-bit codes and eight-bit codes? This seemingly difficult problem is solved using what is known as a "prefix-free variable-length" encoding.
In such an encoding, any number of bits can be used to represent any glyph, and glyphs not present in the message are simply not encoded. However, in order to be able to recover the information, no bit pattern that encodes a glyph is allowed to be the prefix of any other encoding bit pattern. This allows the encoded bitstream to be read bit by bit, and whenever a set of bits is encountered that represents a glyph, that glyph can be decoded. If the prefix-free constraint was not enforced, then such a decoding would be impossible.
Consider the text "AAAAABCD". Using ASCII, encoding this would require 64 bits. If, instead, we encode "A" with the bit pattern "00", "B" with "01", "C" with "10", and "D" with "11" then we can encode this text in only 16 bits; the resulting bit pattern would be "0000000000011011". This is still a fixed-length encoding, however; we’re using two bits per glyph instead of eight. Since the glyph "A" occurs with greater frequency, could we do better by encoding it with fewer bits? In fact we can, but in order to maintain a prefix-free encoding, some of the other bit patterns will become longer than two bits. An optimal encoding is to encode "A" with "0", "B" with "10", "C" with "110", and "D" with "111". (This is clearly not the only optimal encoding, as it is obvious that the encodings for B, C and D could be interchanged freely for any given encoding without increasing the size of the final encoded message.) Using this encoding, the message encodes in only 13 bits to "0000010110111", a compression ratio of 4.9 to 1 (that is, each bit in the final encoded message represents as much information as did 4.9 bits in the original encoding). Read through this bit pattern from left to right and you’ll see that the prefix-free encoding makes it simple to decode this into the original text even though the codes have varying bit lengths.
As a second example, consider the text "THE CAT IN THE HAT". In this text, the letter "T" and the space character both occur with the highest frequency, so they will clearly have the shortest encoding bit patterns in an optimal encoding. The letters "C", "I’ and "N" only occur once, however, so they will have the longest codes.
There are many possible sets of prefix-free variable-length bit patterns that would yield the optimal encoding, that is, that would allow the text to be encoded in the fewest number of bits. One such optimal encoding is to encode spaces with "00", "A" with "100", "C" with "1110", "E" with "1111", "H" with "110", "I" with "1010", "N" with "1011" and "T" with "01". The optimal encoding therefore requires only 51 bits compared to the 144 that would be necessary to encode the message with 8-bit ASCII encoding, a compression ratio of 2.8 to 1.
Input
Output
Sample Input
AAAAABCD THE_CAT_IN_THE_HAT END
Sample Output
64 13 4.9 144 51 2.8题目翻译:表示对英语很痛苦。
者“extra”信息,换句话说,entropy编码删除的信息是没有用的。在第一出现的地方去准确的编写信息。
entropy的高的程度暗含的信息处理“wasted”信息,英文的用ASCII 编写的是信息类型的一种,好很高的
entropy。已经压缩过的信息,例如JPEG图片格式或ZIP压缩,还有小量entropy和没有意义试图 entropy
encoding.
英文编码ASCII有很高程度entropy,因为所有的字符编码使用相同的位数,8位,这是一个事实字母E、L、N
、R、S和T在英文中使用的频率高于其他字母。如果一种方法能够发现用4位去编写字母,然而新的编码将变得小
,包含最初的信息、和更少的entropy。ASCII 使用一适合的位数,然而, it’s easy,自从一种方法能够处
理一个适合位的数字来代表可能符号或字符,如何一个编码方案,四位用于上述信件能够区分四位代码和八位码?
这个看似困难的问题解决了使用所谓的 "prefix-free variable-length"编码。在这样一个编码,可以使用任
意数量的位来表示任何符号,符号并不是出现在消息中不是简单的编码。然而,为了能够恢复信息,不允许位模式
为一种字形编码的前缀其他编码位模式。这使得编码比特流读一点点,每当遇到一组位代表一个字形,字形可以解
码。如果prefix-free约束不执行,那么这样一个解码是不可能的。
考虑到文本为“AAAAABCD”使用ASCII,要用64位,代替,我们用“00”表示A,用“01”表示B,“10”表示
C,“11”表示D然而文本只需要16位,由此产生的位模式将是“0000000000011011”。这是一个适合长度的编
码,我们使用2为来表示字符或字母,然而A的使用频率很高,我们是否可以用更少的位来编码?事实上,我们可以,但是为了维持前缀编码,有些字母的编码可能超过2位,一个可选的编码用“0”表示A,“10”表示B,用“
110”表示C用“111”表示D,使用这种编码,信息编码只需要13位 "0000010110111",压缩率为4.9/1,通读
这一位模式从左到右,你会看到prefix-free编码解码使它简单到原始文本尽管代码不同长度。
第二个例子,考虑文本 "THE CAT IN THE HAT".。在这个文字,字母“T”和空格字符都发生频率最高的,所以
他们显然会有最短的以最优的编码编码二进制模式。字母“C”,“I”和“N”只发生一次,然而,所以他们会有最
长的代码。
可能有许多套prefix-free变长将产生最优编码二进制模式,即允许文本编码在最少的碎片。就是这样一个最
优编码编码空间与“00”,“A”与“100”、“C”与“1110”、“E”与“1111”、“H”与“110”、“我”与
“1010”、“N”与“1011”和“T”与“01”。最优编码因此只需要51位相比,144,需要与8位ASCII编码的信息
编码,压缩比为2.8比1。
#include <iostream>
#include <queue>
#include <cstdio>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str;
while(cin>>str)
{
if(str=="END")
break;
priority_queue<int, vector<int>, greater<int> > qu;
sort(str.begin(),str.end());
char c = str[0];
int t =0;
for(int i=0; i<str.length(); i++) //统计每个字符出现的次数
{
if(str[i]==c)
{
t++;
}else
{
c = str[i];
qu.push(t);
t =1;
}
}
qu.push(t);
int old = str.length()*8;
int new1 = 0;
int a, b;
if(qu.size()==1)new1=qu.top();
while(true)
{
a = qu.top();
qu.pop();
if(qu.empty())
break;
b = qu.top();
qu.pop();
new1 += a+b;
qu.push(a+b);
}
printf("%d %d %.1f\n",old,new1,double(old)/double(new1));
}
return 0;
}
这是一道关于哈夫曼编码应用的题目,要求帮助农夫约翰以最低费用将一块长木板锯成指定长度的小木板。通过优化哈夫曼树的思想,使用优先队列来解决此问题,以避免频繁排序导致的时间浪费。
4万+

被折叠的 条评论
为什么被折叠?



