ter = array_value($config, 'filter');
$arr = array_value($filter, $type);
$enable = array_value($arr, 'enable');
$wordarr = array_value($arr, 'keyword');
if (0 == $enable || empty($wordarr)) return FALSE;
foreach ($wordarr as $_keyword) {
if (!$_keyword) continue;
$r = strpos(strtolower($keyword), strtolower($_keyword));
if (FALSE !== $r) {
$error = $_keyword;
return TRUE;
}
}
return FALSE;
}
// return http://domain.com OR https://domain.com
function url_prefix()
{
$http = ((isset($_SERVER['HTTPS']) && 'on' == $_SERVER['HTTPS']) || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
return $http . $_SERVER['HTTP_HOST'];
}
// 唯一身份ID
function uniq_id()
{
return uniqid(substr(md5(microtime(true) . mt_rand(1000, 9999)), 8, 8));
}
// 生成订单号 14位
function trade_no()
{
$trade_no = str_replace('.', '', microtime(1));
$strlen = mb_strlen($trade_no, 'UTF-8');
$strlen = 14 - $strlen;
$str = '';
if ($strlen) {
for ($i = 0; $i <= $strlen; $i++) {
if ($i < $strlen) $str .= '0';
}
}
return $trade_no . $str;
}
// 生成订单号 16位
function trade_no_16()
{
$explode = explode(' ', microtime());
$trade_no = $explode[1] . mb_substr($explode[0], 2, 6, 'UTF-8');
return $trade_no;
}
// 当前年的天数
function date_year($time = NULL)
{
$time = intval($time) ? $time : time();
return date('L', $time) + 365;
}
// 当前年份中的第几天
function date_z($time = NULL)
{
$time = intval($time) ? $time : time();
return date('z', $time);
}
// 当前月份中的第几天,没有前导零 1 到 31
function date_j($time = NULL)
{
$time = intval($time) ? $time : time();
return date('j', $time);
}
// 当前月份中的第几天,有前导零的2位数字 01 到 31
function date_d($time = NULL)
{
$time = intval($time) ? $time : time();
return date('d', $time);
}
// 当前时间为星期中的第几天 数字表示 1表示星期一 到 7表示星期天
function date_w_n($time = NULL)
{
$time = intval($time) ? $time : time();
return date('N', $time);
}
// 当前日第几周
function date_d_w($time = NULL)
{
$time = intval($time) ? $time : time();
return date('W', $time);
}
// 当前几月 没有前导零1-12
function date_n($time = NULL)
{
$time = intval($time) ? $time : time();
return date('n', $time);
}
// 当前月的天数
function date_t($time = NULL)
{
$time = intval($time) ? $time : time();
return date('t', $time);
}
// 0 o'clock on the day
function clock_zero()
{
return strtotime(date('Ymd'));
}
// 24 o'clock on the day
function clock_twenty_four()
{
return strtotime(date('Ymd')) + 86400;
}
// 8点过期 / expired at 8 a.m.
function eight_expired($time = NULL)
{
$time = intval($time) ? $time : time();
// 当前时间大于8点则改为第二天8点过期
$life = date('G') <= 8 ? (strtotime(date('Ymd')) + 28800 - $time) : clock_twenty_four() - $time + 28800;
return $life;
}
// 24点过期 / expired at 24 a.m.
function twenty_four_expired($time = NULL)
{
$time = intval($time) ? $time : time();
$twenty_four = clock_twenty_four();
$life = $twenty_four - $time;
return $life;
}
/**
* @param $url 提交地址
* @param string $post POST数组 / 空为GET获取数据 / $post='GET'获取连续跳转最终URL
* @param string $cookie cookie
* @param int $timeout 超时
* @param int $ms 设为1是毫秒
* @return mixed 返回数据
*/
function https_request($url, $post = '', $cookie = '', $timeout = 30, $ms = 0)
{
if (empty($url)) return FALSE;
if (version_compare(PHP_VERSION, '5.2.3', '<')) {
$ms = 0;
$timeout = 30;
}
is_array($post) and $post = http_build_query($post);
// 没有安装curl 使用http的形式,支持post
if (!extension_loaded('curl')) {
//throw new Exception('server not install CURL');
if ($post) {
return https_post($url, $post, $cookie, $timeout);
} else {
return http_get($url, $cookie, $timeout);
}
}
is_array($cookie) and $cookie = http_build_query($cookie);
$curl = curl_init();
// 返回执行结果,不输出
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//php5.5跟php5.6中的CURLOPT_SAFE_UPLOAD的默认值不同
if (class_exists('\CURLFile')) {
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
} else {
defined('CURLOPT_SAFE_UPLOAD') and curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
}
// 设定请求的RUL
curl_setopt($curl, CURLOPT_URL, $url);
// 设定返回信息中包含响应信息头
if (ini_get('safe_mode') && ini_get('open_basedir')) {
// $post参数必须为GET
if ('GET' == $post) {
// 安全模式时将头文件的信息作为数据流输出
curl_setopt($curl, CURLOPT_HEADER, true);
// 安全模式采用连续抓取
curl_setopt($curl, CURLOPT_NOBODY, true);
}
} else {
curl_setopt($curl, CURLOPT_HEADER, false);
// 允许跳转10次
curl_setopt($curl, CURLOPT_MAXREDIRS, 10);
// 使用自动跳转,返回最后的Location
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
}
$ua1 = 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1';
$ua = empty($_SERVER["HTTP_USER_AGENT"]) ? $ua1 : $_SERVER["HTTP_USER_AGENT"];
curl_setopt($curl, CURLOPT_USERAGENT, $ua);
// 兼容HTTPS
if (FALSE !== stripos($url, 'https://')) {
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
//ssl版本控制
//curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
curl_setopt($curl, CURLOPT_SSLVERSION, true);
}
$header = array('Content-type: application/x-www-form-urlencoded;charset=UTF-8', 'X-Requested-With: XMLHttpRequest');
$cookie and $header[] = "Cookie: $cookie";
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
if ($post) {
// POST
curl_setopt($curl, CURLOPT_POST, true);
// 自动设置Referer
curl_setopt($curl, CURLOPT_AUTOREFERER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
}
if ($ms) {
curl_setopt($curl, CURLOPT_NOSIGNAL, true); // 设置毫秒超时
curl_setopt($curl, CURLOPT_TIMEOUT_MS, intval($timeout)); // 超时毫秒
} else {
curl_setopt($curl, CURLOPT_TIMEOUT, intval($timeout)); // 秒超时
}
//优先解析 IPv6 超时后IPv4
//curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
// 返回执行结果
$output = curl_exec($curl);
// 有效URL,输出URL非URL页面内容 CURLOPT_RETURNTRANSFER 必须为false
'GET' == $post and $output = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
curl_close($curl);
return $output;
}
function save_image($img)
{
$ch = curl_init();
// 设定请求的RUL
curl_setopt($ch, CURLOPT_URL, $img);
// 设定返回信息中包含响应信息头 启用时会将头文件的信息作为数据流输出
//curl_setopt($ch, CURLOPT_HEADER, false);
//curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
// true表示$html,false表示echo $html
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
// 计算字串宽度:剧中对齐(字体大小/字串内容/字体链接/背景宽度/倍数)
function calculate_str_width($size, $str, $font, $width, $multiple = 2)
{
$box = imagettfbbox($size, 0, $font, $str);
return ($width - $box[4] - $box[6]) / $multiple;
}
// 搜索目录下的文件 比对文件后缀
function search_directory($path)
{
if (is_dir($path)) {
$paths = scandir($path);
foreach ($paths as $val) {
$sub_path = $path . '/' . $val;
if ('.' == $val || '..' == $val) {
continue;
} else if (is_dir($sub_path)) {
//echo '目录名:' . $val . ' ';
search_directory($sub_path);
} else {
//echo ' 最底层文件: ' . $path . '/' . $val . '
';
$ext = strtolower(file_ext($sub_path));
if (in_array($ext, array('php', 'asp', 'jsp', 'cgi', 'exe', 'dll'), TRUE)) {
echo '异常文件:' . $sub_path . ' ';
}
}
}
}
}
// 一维数组转字符串 $sign待签名字符串 $url为urlencode转码GET参数字符串
function array_to_string($arr, &$sign = '', &$url = '')
{
if (count($arr) != count($arr, 1)) throw new Exception('Does not support multi-dimensional array to string');
// 注销签名
unset($arr['sign']);
// 排序
ksort($arr);
reset($arr);
// 转字符串做签名
$url = '';
$sign = '';
foreach ($arr as $key => $val) {
if (empty($val) || is_array($val)) continue;
$url .= $key . '=' . urlencode($val) . '&';
$sign .= $key . '=' . $val . '&';
}
$url = substr($url, 0, -1);
$url = htmlspecialchars($url);
$sign = substr($sign, 0, -1);
}
// 私钥生成签名
function rsa_create_sign($data, $key, $sign_type = 'RSA')
{
if (!function_exists('openssl_sign')) throw new Exception('OpenSSL extension is not enabled');
if (!defined('OPENSSL_ALGO_SHA256')) throw new Exception('Only versions above PHP 5.4.8 support SHA256');
$key = wordwrap($key, 64, "\n", true);
if (FALSE === $key) throw new Exception('Private Key Error');
$key = "-----BEGIN RSA PRIVATE KEY-----\n$key\n-----END RSA PRIVATE KEY-----";
if ('RSA2' == $sign_type) {
openssl_sign($data, $sign, $key, OPENSSL_ALGO_SHA256);
} else {
openssl_sign($data, $sign, $key, OPENSSL_ALGO_SHA1);
}
// 加密
return base64_encode($sign);
}
// 公钥验证签名
function rsa_verify_sign($data, $sign, $key, $sign_type = 'RSA')
{
$key = wordwrap($key, 64, "\n", true);
if (FALSE === $key) throw new Exception('Public Key Error');
$key = "-----BEGIN PUBLIC KEY-----\n$key\n-----END PUBLIC KEY-----";
// 签名正确返回1 签名不正确返回0 错误-1
if ('RSA2' == $sign_type) {
$result = openssl_verify($data, base64_decode($sign), $key, OPENSSL_ALGO_SHA256);
} else {
$result = openssl_verify($data, base64_decode($sign), $key, OPENSSL_ALGO_SHA1);
}
return $result === 1;
}
// Array to xml array('appid' => 'appid', 'code' => 'success')
function array_to_xml($arr)
{
if (!is_array($arr) || empty($arr)) throw new Exception('Array Error');
$xml = "";
foreach ($arr as $key => $val) {
if (is_numeric($val)) {
$xml .= "<" . $key . ">" . $val . "" . $key . ">";
} else {
$xml .= "<" . $key . ">" . $key . ">";
}
}
$xml .= " ";
return $xml;
}
// Xml to array
function xml_to_array($xml)
{
if (!$xml) throw new Exception('XML error');
$old = libxml_disable_entity_loader(true);
// xml解析
$result = (array)simplexml_load_string($xml, null, LIBXML_NOCDATA | LIBXML_COMPACT);
// 恢复旧值
if (FALSE === $old) libxml_disable_entity_loader(false);
return $result;
}
// 逐行读取
function well_import($file)
{
if ($handle = fopen($file, 'r')) {
while (!feof($handle)) {
yield trim(fgets($handle));
}
fclose($handle);
}
}
// 计算总行数
function well_import_total($file, $key = 'well_import_total')
{
static $cache = array();
if (isset($cache[$key])) return $cache[$key];
$count = cache_get($key);
if (NULL === $count) {
$count = 0;
$globs = well_import($file);
while ($globs->valid()) {
++$count;
$globs->next(); // 指向下一个
}
$count and cache_set($key, $count, 300);
}
return $cache[$key] = $count;
}
$g_dir_file = FALSE;
function well_search_dir($path)
{
global $g_dir_file;
FALSE === $g_dir_file and $g_dir_file = array();
if (is_dir($path)) {
$paths = scandir($path);
foreach ($paths as $val) {
$sub_path = $path . '/' . $val;
if ('.' == $val || '..' == $val) {
continue;
} else if (is_dir($sub_path)) {
well_search_dir($sub_path);
} else {
$g_dir_file[] = $sub_path;
}
}
}
return $g_dir_file;
}
?>树和 Huffman Tree 哈夫曼树-阿南达文事网
树和 Huffman Tree 哈夫曼树 编程日记 110 0
更新时间:2025-05-10 13:02:28
树和 Huffman Tree 哈夫曼树
基础概念补充
什么是树
这是一棵有12个节点的树(其中,我们定义这棵树每个节点上的数字只是它的编号,没有其他意义)。
1 2 3 4 5 6 7 8 9 10 11 12
其中,如果我们定义1号点为根,则其下方与它直接相连的节点都是它的子树(即:1号点的子节点为2, 3, 4号节点)。对于子节点们,它们上面那个就是自己的父节点(即:节点2, 3, 4的父节点都是1号节点)。
不难看出:
8号节点的子节点为11号和12号节点 7号节点的父节点为3号节点 5号节点没有子节点 1号节点(根)没有父节点
由其中某个点及以下节点组成的集合,称为一棵子树。例如,节点8, 11, 12组成的集合,是节点3的子树。 所有末端的节点,都是这棵树的叶节点
。如,节点6就是这棵树的叶节点,节点11也是,节点4亦然。
什么是节点之间路径长度
看上面那棵树。我们定每条路的长度为1,则从点A到点B的路径长度为这两个点之间每条路的长度和。 如,从11号点走到6号点,路径长度为3,途径8号点和3号点。 如,从5号点走到10号点,路径长度为5,途径2号点,1号点,3号点和7号点。 同样,你可以自己算一算其他点之间的路径长度。
什么是树的路径长度
我们定义一棵树的路径长度为从根节点到所有叶节点的路径长度之和。 在上图中,我们定义1号点为根,则4、5、6、9、10、11、12号点为叶子节点。记叶节点编号为x ,根节点到叶节点的距离为dist(x) ,易得:
x dist(x) 4 1 5 2 6 2 9 2 10 3 11 3 12 3 ∑ d i s t ( x ) \sum{dist(x)} ∑dist(x) 16
(悄悄说:笔者希望上表横向排列,即,表头在左边,但不知道该怎么做……在此向诸位熟悉 Markdown 的大佬请教 qwq) 由上表可知,这棵树的路径长度为16.
什么是树的带权路径长度
上表中,我们计算那棵树的路径长度为 ∑ d i s t ( x ) \sum{dist(x)} ∑dist(x). 如果我们认为每个叶子节点都有一个权值(记编号为x 的点的权值为value(x) ),则树的带权路径长度为 ∑ ( v a l u e ( x ) ⋅ d i s t ( x ) ) \sum{(value(x)·dist(x))} ∑(value(x)⋅dist(x)). 我们假设上述那棵树的叶节点权值如下:
x value(x) 4 20 5 33 6 24 9 46 10 58 11 4 12 16
则可计算树的带权路径长度:
x dist(x) value(x) value(x) · dist(x) 4 1 20 20 5 2 33 66 6 2 24 48 9 2 46 92 10 3 58 174 11 3 4 12 12 3 16 48 ∑ ( v a l u e ( x ) ⋅ d i s t ( x ) ) \sum{(value(x)·dist(x))} ∑(value(x)⋅dist(x)) 460
这棵树的带权路径长度为460 .
什么是森林
好多棵树放在一起,就是森林。比如这张图展示的就是一个森林:
1 2 3 4 5 6 7 8 9 10 11 12
图中,点 1, 2, 3, 4, 5 构成一棵树。 点 6 自己是一个只有一个节点的树。 点 7 自己是一个只有一个节点的树。 点 8, 10, 11, 12 构成一棵树。 点 9 自己是一个只有一个节点的树。
什么是二叉树
每个节点的子节点数最多为2的树,是二叉树。如图,这是一颗二叉树:
1 2 3 4 5 6 7 8 9 10 11 12
图中,每个节点的左右子节点,分别称为这个节点的左、右子节点。该节点及向下的所有节点组成的集合称为子树。于是,某节点的左、右子节点及以下的节点集合,分别称为左子树
和右子树
。 不难看出,不是每个节点都同时拥有左右子树。比如图中的6号点,它拥有一棵子树。由于笔者水平有限,画不出左右关系,我们暂时认为12号点是它的右子树,那么它没有左子树。 同样,节点4、节点7和节点10也都只有一个子树。
哈夫曼树
什么是哈夫曼树
假如我们有好多个带权的单节点树。如图(这里,我们定义圆圈内的数字是权值 ):
20 33 24 46 58 4 16
现在,我们需要向图中添加一些不作为叶节点的 节点,将它们和原来的带权节点连接起来,构成一棵二叉树。该二叉树中,所有新加入的节点都不是叶节点,而所有原有的带权节点都是叶节点。如图所示,我们可以构造出一棵二叉树:
20 33 24 46 58 58 16
从新加入的节点中选取一个根(为方便,我们认为画图时最上方的节点是根节点),这样可以得到树的权值。 不难计算,这棵树的带权路径长度是663 .
同样,我们还可以构造出另外模样的二叉树:
20 33 24 46 58 4 16
不难算出,这棵树的带权路径长度是:752 .
显然,第二棵树的带权路径长度比第一棵树大。 事实上,我们可以构造出非常多棵这样的二叉树。其中带权路径长度最短的 那棵二叉树,即为哈夫曼树
。 对于上述带权叶节点,构造出的哈夫曼树如图:
24 33 46 58 4 16 20
如图,这棵树的带权路径长度是519 . 找不到带权路径长度比它小的构造方法(相等是可以的,但找不到更小的),不信你可以试试。
观察并思考,可以发现,想要构造哈夫曼树,就要让权值大的节点尽可能靠近根,权值小的节点相对远离根。于是,我们得到一种构造方法:
从所有根节点中(起初,所有节点都是根,因为所有节点都没有父节点),寻找到权值最小的两个。 使用一个节点,作为它们的根,将它们连接起来。该节点的权值设为两个子节点的权值之和。 回到步骤1,直到森林中只有一棵树。
我们跟着这个步骤尝试一下。
初始状态:
24 33 46 58 4 16 20
我们发现,权值最小的根节点,权值为4和16. 于是,我们将它们连起来,并将新的根节点权值设为它们的和:4+16=20
20 24 33 46 58 4 16 20
接下来,找到权值最小的两个根节点。他们的权值分别是20,20. 将它们连接,新的根节点权值为:20+20=40
20 40 24 33 46 58 4 16 20
继续寻找,找到权值分别为24和33的点。连接后,新的根节点权值为:24+33=57
20 40 57 24 33 46 58 4 16 20
继续寻找,找到权值分别为40和46的点。连接后,新的根节点权值为:40+46=86
20 40 57 86 24 33 46 58 4 16 20
继续寻找,找到权值分别为57和58的点。连接后,新的根节点权值为:57+58=115
20 40 57 86 115 24 33 46 58 4 16 20
继续寻找,找到权值分别为86和115的点(当然,也只剩这两个点了)。连接后,新的根节点权值为:86+115=201
20 40 57 86 115 201 24 33 46 58 4 16 20
至此,森林中只有一棵树。这棵树便是哈夫曼树。你可以算一下它的带权路径长度。 你可能觉得,这棵树跟上面那棵哈夫曼树不太一样。但是,它们其实是同构的,即,随意交换任意节点的左右孩子后,它们会变成同一棵树。
哈夫曼树的应用
借助哈夫曼树,我们可以实现很多神奇的操作,如对 ASCII 字符串文本的压缩。 [枫铃树] 使用 Huffman Tree 哈夫曼树实现对 ASCII 字符串文本的压缩与解压
本文发布于:2024-11-10,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签: 树和 Huffman Tree 哈夫曼树
发布评论