<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Narcissus's blog</title>
    <description>Narcissus' blog</description>
    <link>https://narcissuscyn.github.io/</link>
    <atom:link href="https://narcissuscyn.github.io/feed.xml" rel="self" type="application/rss+xml"/>
    <pubDate>Fri, 23 Aug 2019 03:30:25 +0000</pubDate>
    <lastBuildDate>Fri, 23 Aug 2019 03:30:25 +0000</lastBuildDate>
    <generator>Jekyll v3.8.5</generator>
    
      <item>
        <title>RNN原理、公式推导及python实现</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#rnn原理及pytorch实现&quot; id=&quot;markdown-toc-rnn原理及pytorch实现&quot;&gt;RNN原理及pytorch实现&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#图像理解&quot; id=&quot;markdown-toc-图像理解&quot;&gt;图像理解&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#注意细节&quot; id=&quot;markdown-toc-注意细节&quot;&gt;注意细节&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#公式理解&quot; id=&quot;markdown-toc-公式理解&quot;&gt;公式理解&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#正向传播公式&quot; id=&quot;markdown-toc-正向传播公式&quot;&gt;正向传播公式&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#反向求导bpttback-propagation-through-time&quot; id=&quot;markdown-toc-反向求导bpttback-propagation-through-time&quot;&gt;反向求导（BPTT：back propagation through time）&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;rnn原理及pytorch实现&quot;&gt;RNN原理及pytorch实现&lt;/h3&gt;

&lt;h4 id=&quot;图像理解&quot;&gt;图像理解&lt;/h4&gt;

&lt;img src=&quot;https://narcissuspicbed.oss-cn-hangzhou.aliyuncs.com/rnn-structure.png&quot; alt=&quot;&quot; /&gt;

&lt;h5 id=&quot;注意细节&quot;&gt;注意细节&lt;/h5&gt;

&lt;ul&gt;
  &lt;li&gt;RNN只有这四个参数：$U,W​$,对于RNN和特定任务相结合，使用隐藏状态的输出，得到预测结果，也就是分类器部分，才有分类器的参数$V​$，并不是RNN的参数。&lt;/li&gt;
  &lt;li&gt;
    横向展开的每个timestep共享权重。
  &lt;/li&gt;
  &lt;li&gt;
    pytorch中的激活函数：tanh 或者 relu,因为pytorch直接使用的cudnn接口，cudnn中只支持这两种。
  &lt;/li&gt;
  &lt;li&gt;
    pytorch中，RNN的默认输入形状是(seq_len, batch_size, input_size)，batch_size位于第二维度，因为cuDNN中RNN的API就是batch_size在第二维度！把batch_first设置为True，可以将batch_size和序列长度seq_len对换位置。batch first意味着模型的输入（一个Tensor）在内存中存储时，先存储第一个sequence，再存储第二个… 而如果是seq_len first，模型的输入在内存中，先存储所有序列的第一个单元，然后是第二个单元.

    &lt;img src=&quot;https://narcissuspicbed.oss-cn-hangzhou.aliyuncs.com/RNN-%E8%BE%93%E5%87%BA%E5%AD%98%E5%82%A8.png&quot; alt=&quot;&quot; /&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;公式理解&quot;&gt;公式理解&lt;/h4&gt;

&lt;h5 id=&quot;正向传播公式&quot;&gt;正向传播公式&lt;/h5&gt;

RNN迭代式
&lt;script type=&quot;math/tex&quot;&gt;s_t=tanh(Ux_t+Ws_{t-1})&lt;/script&gt;
分类器
&lt;script type=&quot;math/tex&quot;&gt;y_t=softmax(Vs_t)&lt;/script&gt;
损失:把整个timestep的数据当成一个训练数据。
&lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
\begin{align}
E_t(y_t,\hat{y_t})&amp;=-y_tlog\hat{y_t}\\
E(y,\hat{y})&amp;=\sum_tE_t(y_t,\hat{y_t})\\
&amp;=-\sum_ty_tlog\hat{y_t}
\end{align} %]]&gt;&lt;/script&gt;

&lt;h5 id=&quot;反向求导bpttback-propagation-through-time&quot;&gt;反向求导（BPTT：back propagation through time）&lt;/h5&gt;

BPTT是关于标准RNN的名称。对每个参数的求导，都要各个timestep加起来。即：
&lt;script type=&quot;math/tex&quot;&gt;\frac{\partial{E}}{\partial{W}}=\sum_t\frac{\partial{E_t}}{\partial{W}}\\
\frac{\partial{E}}{\partial{U}}=\sum_t\frac{\partial{E_t}}{\partial{U}}\\
\frac{\partial{E}}{\partial{V}}=\sum_t\frac{\partial{E_t}}{\partial{V}}&lt;/script&gt;

&lt;img src=&quot;https://github.com/pangolulu/rnn-from-scratch/raw/master/figures/rnn-bptt-with-gradients.png&quot; alt=&quot;img&quot; /&gt;

以$\frac{\partial{E_1}}{\partial{W}}$为例：

&lt;img src=&quot;https://github.com/pangolulu/rnn-from-scratch/raw/master/figures/rnn-compuattion-graph.png&quot; alt=&quot;img&quot; /&gt;

&lt;img src=&quot;https://github.com/pangolulu/rnn-from-scratch/raw/master/figures/rnn-compuattion-graph_2.png&quot; alt=&quot;img&quot; /&gt;

1）$V$的反向求导比较简单，&lt;script type=&quot;math/tex&quot;&gt;\frac{\partial{E_t}}{\partial{V}}&lt;/script&gt;,与等无时间序列无关
&lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
\begin{align}
E_t&amp;=-y_t^Tlog(\hat{y_t})\\
z_t&amp;=Vs_t\\
\hat{y_t}&amp;=softmax(z_t)
\end{align} %]]&gt;&lt;/script&gt;

</description>
        <pubDate>Sun, 28 Jul 2019 17:40:41 +0000</pubDate>
        <link>https://narcissuscyn.github.io/2019/07/28/Naive-RNN/</link>
        <guid isPermaLink="true">https://narcissuscyn.github.io/2019/07/28/Naive-RNN/</guid>
        
        <category>RNN</category>
        
        
        <category>深度学习</category>
        
      </item>
    
      <item>
        <title>Word Embedding models的深入理解</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#word-embedding-深入理解&quot; id=&quot;markdown-toc-word-embedding-深入理解&quot;&gt;Word Embedding 深入理解&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#distributional-semantics-history&quot; id=&quot;markdown-toc-distributional-semantics-history&quot;&gt;Distributional Semantics History&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#word-embedding-history&quot; id=&quot;markdown-toc-word-embedding-history&quot;&gt;Word Embedding History&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#word-embedding-models&quot; id=&quot;markdown-toc-word-embedding-models&quot;&gt;Word embedding models&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#embedding-layer&quot; id=&quot;markdown-toc-embedding-layer&quot;&gt;Embedding Layer&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#notational-standards&quot; id=&quot;markdown-toc-notational-standards&quot;&gt;notational standards&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#language-modelling&quot; id=&quot;markdown-toc-language-modelling&quot;&gt;Language Modelling&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#classic-neural-language-model&quot; id=&quot;markdown-toc-classic-neural-language-model&quot;&gt;Classic neural language model&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#cw-model&quot; id=&quot;markdown-toc-cw-model&quot;&gt;C&amp;amp;W model&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

显示不正常可看&lt;a href=&quot;https://github.com/Narcissuscyn/Algorithm/blob/master/WordEmbedding_1_models.pdf&quot;&gt;pdf版本&lt;/a&gt;

&lt;h1 id=&quot;word-embedding-深入理解&quot;&gt;Word Embedding 深入理解&lt;/h1&gt;

Well-known models for learning word embeddings based on language modelling. 这些无监督方法学得的词向量已经在很多NLP任务中代替了传统的“分布式特征”（distributional feature，since the underlying semantic theory is called &lt;a href=&quot;https://en.wikipedia.org/wiki/Distributional_semantics&quot;&gt;distributional semantics&lt;/a&gt;）,比如Brown clusters以及LSA 特征。如今盛行的Word Embedding都是指的“dense representations of words in a low-dimensional vector space”，还可以表示为&lt;em&gt;word vectors&lt;/em&gt; , &lt;em&gt;distributed representations&lt;/em&gt;, semantic vector space or simply word space。Word Embedding表示的向量能表示语义相似性，可以用来表示自身的语义特征，计算不同词之间的语义相似性，也可以作为一种表示，应用到其他NLP任务中去，like text classification, document clustering, part of speech tagging, named entity recognition, sentiment analysis, and so on.

&lt;h2 id=&quot;distributional-semantics-history&quot;&gt;Distributional Semantics History&lt;/h2&gt;

Idea: 相对于形式化的语言学，语言上下文信息能形成一个合理的关于语言项（如word）的表示。

19世纪八九十年代就有这种semantic representation的应用。Methods for using &lt;strong&gt;automatically generated contextual features&lt;/strong&gt; were developed more or less simultaneously around 1990 in several different research areas. LSA/LSI就是最有影响力的模型，也是现今topic models的先驱；与此同时也有利用这些contextual representation的人工神经网络模型，如SOM,SRN，他们是如今&lt;strong&gt;神经语言模型&lt;/strong&gt;的先驱。

后来的模型几乎都是对原有模型的一些细微改良，比如topic models里面的PLSA,LDA都是对LSA的改良；neural language moddel基于SRN、CNN、Autoencoders等。Distrubutional semantic models都是基于HAL等。主要区别是他们使用的是不同类型的contextual information，而不同的上下文信息表达了不同的语义相似性。

&lt;blockquote&gt;
  The main difference between these various models is the type of contextual information they use. LSA and topic models use &lt;em&gt;documents&lt;/em&gt; as contexts, which is a legacy from their roots in information retrieval. Neural language models and distributional semantic models instead use &lt;em&gt;words&lt;/em&gt; as contexts, which is arguably more natural from a linguistic and cognitive perspective. These different contextual representations capture different types of semantic similarity; the document-based models capture &lt;strong&gt;semantic relatedness&lt;/strong&gt; (e.g. “boat” – “water”) while the word-based models capture &lt;strong&gt;semantic similarity&lt;/strong&gt; (e.g. “boat” – “ship”). This very basic difference is too often misunderstood.
&lt;/blockquote&gt;

这里对于普遍的错误认识还有两个点需要说明：

&lt;ul&gt;
  &lt;li&gt;没必要为了得到好的word embedding而使用&lt;strong&gt;深度&lt;/strong&gt;神经网络模型，因为目前的CBOW和Skip-gram模型都是和SRN相似的浅层神经网络模型，却已经取得了比较成功的效果。&lt;/li&gt;
  &lt;li&gt;There is no qualitative difference between (current) &lt;strong&gt;predictive* neural network models&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;count-based&lt;/em&gt; distributional semantics models.&lt;/strong&gt; Rather, they are different computational means to arrive at the same type of semantic model。&lt;/li&gt;
&lt;/ul&gt;

那么现在最新的一些语义模型怎么样呢？

What about the current state of the art? The boring answer is that &lt;u&gt;it depends on what task you want to solve, and how much effort you want to spend on optimizing the model.（现在的模型取决于你要解决什么样的任务以及你对模型的优化做了多大努力）&lt;/u&gt; The somewhat more enjoyable answer is that &lt;u&gt;you will probably do fine whichever current method you choose, since they are more or less equivalent（无论你选择哪个模型，你都能取得差不多较好的效果，因为他们多多少少都是等同的）&lt;/u&gt;. A good bet is to use a &lt;strong&gt;factorized model&lt;/strong&gt; – either using explicit factorization of a distributional semantic model (available in e.g. the &lt;a href=&quot;https://github.com/jimmycallin/pydsm&quot;&gt;PyDSM&lt;/a&gt; python library or the &lt;a href=&quot;http://nlp.stanford.edu/projects/glove/&quot;&gt;GloVe&lt;/a&gt;implementation), or using a neural network model like those implemented in &lt;a href=&quot;https://code.google.com/p/word2vec/&quot;&gt;word2vec&lt;/a&gt; – since they produce state of the art results (&lt;a href=&quot;http://aclweb.org/anthology/D/D15/D15-1024.pdf&quot;&gt;Österlund et al., 2015&lt;/a&gt;) and are robust across a wide range of semantic tasks (&lt;a href=&quot;http://aclweb.org/anthology/D/D15/D15-1036.pdf&quot;&gt;Schnabel et al., 2015&lt;/a&gt;).

&lt;h2 id=&quot;word-embedding-history&quot;&gt;Word Embedding History&lt;/h2&gt;

2003, Bengio et al.提出术语“word embedding”,并训练神经网络参数；

2008年，Collobert and Weston 提出预训练word embedding的应用；

2013年，Mikolov et al. 提出了最受欢迎的 &lt;strong&gt;word2vec&lt;/strong&gt; 允许无缝训练以及使用预训练word embedding;

2014年，Pennington et al. 放出GloVe.

词向量是少数无监督学习的成功应用。  they don’t require expensive annotation, can be derived from large unannotated corpora that are readily available. Pre-trained embeddings can then be used in downstream tasks that use small amounts of labeled data.

&lt;h2 id=&quot;word-embedding-models&quot;&gt;Word embedding models&lt;/h2&gt;

&lt;h4 id=&quot;embedding-layer&quot;&gt;Embedding Layer&lt;/h4&gt;

在神经网络中，语料通过词典表示后作为输入，然后通过网络第一层将输入embed成低维向量，这个第一维就是Embedding Layer。但这些方法和Word2vec是有所区别的，前者将word embedding当作一个副产品输出，而后者则明确的将Word embedding的生成作为目标，两者的区别就是：

1）计算复杂度的不一样，计算复杂度是一个非常关键的问题，通过深度神经网络来生成word embedding是很昂贵的，这也就是为什么2013年才火起来的原因。

2）训练目标不一样。word2vec和glove是产生的通用word embedding relationship，对那些不依赖这种相似性的任务来说，并不能产生太大帮助的，比如boat和ship比较具有相关性，而有些任务中可能需要boat和water具有相关性；但是regular neural network不一样，他们产生的是task-specific的embeddings。对于依赖于semantically coherent representations的任务，如语言模型，会和word embedding models产生相似的word embedding。

Word embedding models are often evaluated using &lt;a href=&quot;https://en.wikipedia.org/wiki/Perplexity&quot;&gt;perplexity&lt;/a&gt;, a cross-entropy based measure borrowed from language modelling.

&lt;h4 id=&quot;notational-standards&quot;&gt;notational standards&lt;/h4&gt;

&lt;ul&gt;
  &lt;li&gt;T training words $w_1, w_2, w_3, \cdots, w_T$&lt;/li&gt;
  &lt;li&gt;vocabulary V&lt;/li&gt;
  &lt;li&gt;context of n words&lt;/li&gt;
  &lt;li&gt;input embedding $v_w$&lt;/li&gt;
  &lt;li&gt;input embedding $v’_w$&lt;/li&gt;
  &lt;li&gt;model outputs some score $f_\theta(x)$&lt;/li&gt;
  &lt;li&gt;Objective function $J_\theta$&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;language-modelling&quot;&gt;Language Modelling&lt;/h3&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Task:基于n-gram语言模型： 给定n-1个前面的词，计算下一个词的概率：$p(w_t :&lt;/td&gt;
      &lt;td&gt;: w_{t-1} , \cdots w_{t-n+1})$&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

基于&lt;a href=&quot;https://web.stanford.edu/class/cs124/lec/languagemodeling.pdf&quot;&gt;链式法则和Markov假设&lt;/a&gt;，整个sentence或者document的概率就是：
&lt;script type=&quot;math/tex&quot;&gt;p(w_1 , \cdots , w_T) = \prod\limits_i p(w_i \: | \: w_{i-1} , \cdots , w_{i-n+1})&lt;/script&gt;
如何计算每个词的概率呢？可以根据n-gram出现的频率来计算：
&lt;script type=&quot;math/tex&quot;&gt;p(w_t \: | \: w_{t-1} , \cdots , w_{t-n+1}) = \dfrac{count(w_{t-n+1}, \cdots , w_{t-1},w_t)}{count({w_{t-n+1}, \cdots , w_{t-1}})}&lt;/script&gt;
而在神经网络模型中，就是通过下面softmax计算得到：
&lt;script type=&quot;math/tex&quot;&gt;p(w_t \: | \: w_{t-1} , \cdots , w_{t-n+1}) = \dfrac{\text{exp}({h^\top v'_{w_t}})}{\sum_{w_i \in V} \text{exp}({h^\top v'_{w_i}})}&lt;/script&gt;
$h^\top v’_{w_t}$ computes the (&lt;strong&gt;unnormalized&lt;/strong&gt;) &lt;strong&gt;log-probability&lt;/strong&gt; of word $w_t$, h是网络倒数第二层的输出，we normalize by the sum of the log-probabilities of all words in V,which is computation expensive.

目标函数：
&lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
\begin{align}
J_\theta &amp;= \frac{1}{T} \text{log} \space p(w_1 , \cdots , w_T)\\
&amp;= \frac{1}{T}\sum\limits_{t=1}^T\ \text{log} \space p(w_t \: | \: w_{t-1} , \cdots , w_{t-n+1})
\end{align} %]]&gt;&lt;/script&gt;

&lt;h3 id=&quot;classic-neural-language-model&quot;&gt;Classic neural language model&lt;/h3&gt;

Their model maximizes what we’ve described above as the prototypical neural language model objective (we omit the regularization term for simplicity):

&lt;img src=&quot;http://ruder.io/content/images/2016/04/bengio_language_model.png&quot; alt=&quot;&quot; /&gt;

&lt;center&gt;
  Figure 2: Classic neural language model (Bengio et al., 2003)
&lt;/center&gt;

The general building blocks of their model, however, are still found in all current neural language and word embedding models. These are:（这些层现在的模型中还被使用）

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Embedding Layer&lt;/strong&gt;: a layer that generates word embeddings by multiplying an index vector with a word embedding matrix;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Intermediate Layer(s)&lt;/strong&gt;: one or more layers that produce an intermediate representation of the input, e.g. a fully-connected layer that applies a non-linearity to the concatenation of word embeddings of nn previous words;//这一项可以用LSTM代替&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Softmax Layer&lt;/strong&gt;: the final layer that produces a probability distribution over words in V.//这一项的计算量非常大，one of the key challenges both in neural language models as well as in word embedding models.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;cw-model&quot;&gt;C&amp;amp;W model&lt;/h3&gt;

Word embeddings trained on &lt;strong&gt;a sufficiently large dataset&lt;/strong&gt; carry syntactic and semantic meaning and improve performance on downstream tasks.为了解决计算量的问题，他们使用了新的loss，ranking objective，而不再使用softmax+CE，这个loss能为正确的单词序列产生比错误序列更高的分数，他们使用了一个pairwise ranking criterion：
&lt;script type=&quot;math/tex&quot;&gt;J_\theta\ = \sum\limits_{x \in X} \sum\limits_{w \in V} \text{max} \lbrace 0, 1 - f_\theta(x) + f_\theta(x^{(w)}) \rbrace&lt;/script&gt;
这里是一个hinge loss，其中$x^{w}$是采样的负样本，x为正样本。正样本分数要比负样本的分数至少高1.

&lt;img src=&quot;http://ruder.io/content/images/2016/09/nlp_almost_from_scratch_window_approach.png&quot; alt=&quot;&quot; /&gt;

&lt;center&gt;
  Figure 3: The C&amp;amp;W model without ranking objective (Collobert et al., 2011)
&lt;/center&gt;

</description>
        <pubDate>Mon, 08 Jul 2019 17:40:41 +0000</pubDate>
        <link>https://narcissuscyn.github.io/2019/07/08/WordEmbeddingModels/</link>
        <guid isPermaLink="true">https://narcissuscyn.github.io/2019/07/08/WordEmbeddingModels/</guid>
        
        <category>NLP</category>
        
        
        <category>机器学习</category>
        
      </item>
    
      <item>
        <title>从EncoderDecoder到Transformer</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#encoder-decoder&quot; id=&quot;markdown-toc-encoder-decoder&quot;&gt;Encoder-Decoder&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#横向分析&quot; id=&quot;markdown-toc-横向分析&quot;&gt;横向分析&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#纵向分析&quot; id=&quot;markdown-toc-纵向分析&quot;&gt;纵向分析&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#sequence-to-sequence&quot; id=&quot;markdown-toc-sequence-to-sequence&quot;&gt;Sequence-to-Sequence&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#example&quot; id=&quot;markdown-toc-example&quot;&gt;Example&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#attention&quot; id=&quot;markdown-toc-attention&quot;&gt;Attention&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#attention-in-bahdanau-et-al-2015&quot; id=&quot;markdown-toc-attention-in-bahdanau-et-al-2015&quot;&gt;Attention In Bahdanau et al., 2015&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#attention-or-memory&quot; id=&quot;markdown-toc-attention-or-memory&quot;&gt;Attention or Memory&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#attention-family&quot; id=&quot;markdown-toc-attention-family&quot;&gt;Attention Family&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#attention分类&quot; id=&quot;markdown-toc-attention分类&quot;&gt;Attention分类&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#self-attention&quot; id=&quot;markdown-toc-self-attention&quot;&gt;Self-Attention&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#soft-vs-hard-attention&quot; id=&quot;markdown-toc-soft-vs-hard-attention&quot;&gt;Soft vs Hard Attention&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#global-vs-local-attention&quot; id=&quot;markdown-toc-global-vs-local-attention&quot;&gt;Global vs. Local Attention&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#nmt&quot; id=&quot;markdown-toc-nmt&quot;&gt;NMT&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#读写操作&quot; id=&quot;markdown-toc-读写操作&quot;&gt;读写操作&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#attention机制&quot; id=&quot;markdown-toc-attention机制&quot;&gt;Attention机制&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#content-based-addressing&quot; id=&quot;markdown-toc-content-based-addressing&quot;&gt;Content-based addressing&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#interpolation&quot; id=&quot;markdown-toc-interpolation&quot;&gt;Interpolation&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#location-based-addressing&quot; id=&quot;markdown-toc-location-based-addressing&quot;&gt;Location-based addressing&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#transformer&quot; id=&quot;markdown-toc-transformer&quot;&gt;Transformer&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#key-value-and-query&quot; id=&quot;markdown-toc-key-value-and-query&quot;&gt;Key, Value and Query&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#multi-head-self-attention&quot; id=&quot;markdown-toc-multi-head-self-attention&quot;&gt;Multi-Head Self-Attention&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#encoder&quot; id=&quot;markdown-toc-encoder&quot;&gt;Encoder&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#decoder&quot; id=&quot;markdown-toc-decoder&quot;&gt;Decoder&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#整个transformer结构&quot; id=&quot;markdown-toc-整个transformer结构&quot;&gt;整个Transformer结构&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#referrence&quot; id=&quot;markdown-toc-referrence&quot;&gt;Referrence&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

[TOC]

可能显示有点问题，可查看pdf：https://github.com/Narcissuscyn/Algorithm/blob/master/from_encoder_decoder_to_transformer.pdf

&lt;h2 id=&quot;encoder-decoder&quot;&gt;Encoder-Decoder&lt;/h2&gt;

在Quara上有一个问题：https://www.quora.com/What-is-an-Encoder-Decoder-in-Deep-Learning，其中Rohan Saxena的回答我觉得挺好理解的，从横向和纵向两个方向来解释这个问题。

&lt;h3 id=&quot;横向分析&quot;&gt;横向分析&lt;/h3&gt;

首先说了特征表示在机器学习里面的重要性，从早期的手工特征（如HOG）到现在使用神经网络进行特征学习(The first few layers of a neural network extract features from the data, or in other words map raw inputs to efficient feature representations. The next few layers (typically fully connected layers) mix and match and combine these features to produce an output.)，都是为了得到好的特征表达。

而一些网络结构被设计用来提取有效的特征表达：

&lt;blockquote&gt;
  They use an encoder network to map raw inputs to feature representations, and a decoder network to take this feature representation as input, process it to make its decision, and produce an output. This is called an encoder-decoder network.
&lt;/blockquote&gt;

encoder和decoder是可以分开使用的，但是常常被结合使用以取得好的效果。

&lt;h3 id=&quot;纵向分析&quot;&gt;纵向分析&lt;/h3&gt;

&lt;strong&gt;CNN Encoder-Decoder&lt;/strong&gt;

In a &lt;strong&gt;CNN&lt;/strong&gt;, an encoder-decoder network typically looks like this (a CNN encoder and a CNN decoder):

&lt;img src=&quot;https://qph.fs.quoracdn.net/main-qimg-78a617ec1de942814c3d23dab7de0b24&quot; alt=&quot;img&quot; /&gt;

&lt;a href=&quot;https://arxiv.org/pdf/1511.00561.pdf&quot;&gt;Image credits&lt;/a&gt;

This is a network to perform semantic segmentation of an image. The left half of the network maps raw image pixels to a rich representation of a collection of feature vectors. The right half of the network takes these features, produces an output and maps the output back into the “raw” format (in this case, image pixels).

&lt;strong&gt;RNN Encoder-Decoder&lt;/strong&gt;

In an &lt;strong&gt;RNN&lt;/strong&gt;, an encoder-decoder network typically looks like this (an RNN encoder and an RNN decoder):

&lt;img src=&quot;https://qph.fs.quoracdn.net/main-qimg-febee5b881545802a75c064a84ecf85d&quot; alt=&quot;img&quot; /&gt;

This is a network to predict responses for incoming emails. The left half of the network encodes the email into a feature vector, and the right half of the network decodes the feature vector to produce word predictions.

**Mixed Style Encoder-Decoder **

Note that it is not necessary to use just CNN or just RNN for encoder and decoder. We can mix and match and use a CNN encoder with RNN decoder, or vice versa; any combination can be used which is suitable for the given task.

An example from a paper I recently implemented from scratch, &lt;a href=&quot;https://arxiv.org/abs/1612.03557&quot;&gt;Text-guided Attention Model for Image Captioning&lt;/a&gt; (T-ATT):

&lt;img src=&quot;https://qph.fs.quoracdn.net/main-qimg-9b693c68a48f67f1941ae71d81f0ed38&quot; alt=&quot;img&quot; /&gt;

Look at the parts I have highlighted in red. The STV refers to &lt;a href=&quot;https://arxiv.org/abs/1506.06726&quot;&gt;Skip-Thought Vectors&lt;/a&gt;. STV in itself is an encoder-decoder architecture.

&lt;h2 id=&quot;sequence-to-sequence&quot;&gt;Sequence-to-Sequence&lt;/h2&gt;

Sequence-to-sequence (seq2seq)* 模型，顾名思义，其输入是一个序列，输出也是一个序列，例如输入是英文句子，输出则是翻译的中文。&lt;a href=&quot;https://arxiv.org/pdf/1409.3215.pdf?source=post_page---------------------------&quot;&gt;2014 Google&lt;/a&gt;提出Sequence-to-sequence的概念(待考证)，在这之前也有使用encoder-decoder来解决sequence2sequence任务的，比如Bengio在2014年的&lt;a href=&quot;https://link.zhihu.com/?target=https%3A//arxiv.org/pdf/1406.1078.pdf&quot;&gt;论文&lt;/a&gt;中提出，提供了一种崭新的RNN Encoder-Decoder算法，并且将其应用于机器翻译中。&lt;em&gt;seq2seq&lt;/em&gt; 可以用在很多方面：机器翻译、&lt;em&gt;QA&lt;/em&gt; 系统、文档摘要生成、&lt;em&gt;Image Captioning&lt;/em&gt; (图片描述生成器)。

&lt;h3 id=&quot;example&quot;&gt;Example&lt;/h3&gt;

对于下面这个简单的示例模型，分为encoder-encoder vector-encoder三个部分。

&lt;img src=&quot;https://miro.medium.com/max/773/1*1JcHGUU7rFgtXC_mydUA_Q.jpeg&quot; alt=&quot;&quot; /&gt;

Encoder和Decoder都是一个由RNN堆叠而成的网络，其实Sequence2Sequence的结构主要是使用的encoder-to-decoder的架构。我觉得seq2seq和auto-encoder是encoder-decoder衍生出来的、针对不同任务的框架，Seq2Seq的主要特点就是输入和输出长度可以不一样，而auto-encoder就是为了对输入进行重建。

&lt;h2 id=&quot;attention&quot;&gt;Attention&lt;/h2&gt;

上面所提及的Encoder-Decoder模型是有弊端的：

&lt;ul&gt;
  &lt;li&gt;随着输入信息长度的增加，由于向量长度固定，先前编码好的信息会被后来的信息覆盖，丢失很多信息（当使用RNN作为Encoder时，由于其长短期记忆能力的有限，当输入信息长度变大，信息丢失严重）。中间语义向量无法完全表达整个输入序列的信息。(this fixed-length context vector design is incapability of remembering long sentences.)//(2015年的文章&lt;a href=&quot;https://arxiv.org/pdf/1409.0473.pdf&quot;&gt;Bahdanau et al., 2015&lt;/a&gt;就是针对这个问题的。The attention mechanism was born to help &lt;u&gt;**memorize long source sentences**&lt;/u&gt; in neural machine translation(&lt;a href=&quot;https://arxiv.org/pdf/1409.0473.pdf&quot;&gt;Bahdanau et al., 2015&lt;/a&gt;))。&lt;/li&gt;
  &lt;li&gt;而且，每个输入的贡献都是一样的。&lt;/li&gt;
&lt;/ul&gt;

因此，在很多方面都出现了改进的模型，包括以下方面：s

&lt;ul&gt;
  &lt;li&gt;
    &lt;a href=&quot;https://arxiv.org/pdf/1409.3215.pdf?source=post_page---------------------------&quot;&gt;Reversing the order of the input sequence&lt;/a&gt;.
  &lt;/li&gt;
  &lt;li&gt;
    &lt;a href=&quot;http://arxiv.org/abs/1410.4615&quot;&gt;feeding an input sequence twice&lt;/a&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
  I consider the approach of reversing a sentence a “hack”. It makes things work better in practice, but it’s not a principled solution. Most translation benchmarks are done on languages like French and German, which are quite similar to English (even Chinese word order is quite similar to English). But there are languages (like Japanese) where the last word of a sentence could be highly predictive of the first word in an English translation. In that case, reversing the input would make things worse. So, what’s an alternative? Attention Mechanisms.//某些时候是不可行的
&lt;/blockquote&gt;

&lt;ul&gt;
  &lt;li&gt;
    Using LSTM or GRU cells.
  &lt;/li&gt;
  &lt;li&gt;
    &lt;a href=&quot;http://www.wildml.com/2016/01/attention-and-memory-in-deep-learning-and-nlp/?source=post_page---------------------------&quot;&gt;Introducing Attention mechanism&lt;/a&gt;.
  &lt;/li&gt;
&lt;/ul&gt;

而Attention就是一种通用的方法，在这部分呢，就来学习一下Attention 的思想.

神经网络中的注意机制基于人类中发现的视觉注意机制：

&lt;blockquote&gt;
  Attention Mechanisms in Neural Networks are (very) loosely based on the visual attention mechanism found in humans. Human visual attention is well-studied and while there exist different models, all of them essentially come down to being able to focus on a certain region of an image with “high resolution” while perceiving the surrounding image in “low resolution”, and then adjusting the focal point over time.
&lt;/blockquote&gt;

在早期就有使用这种attention的思想，但是最近几年才在深度学习领域火起来，下面举一个机器翻译里面应用attention的&lt;a href=&quot;https://arxiv.org/abs/1409.0473&quot;&gt;例子&lt;/a&gt;。

&lt;h3 id=&quot;attention-in-bahdanau-et-al-2015&quot;&gt;Attention In Bahdanau et al., 2015&lt;/h3&gt;

&lt;img src=&quot;https://lilianweng.github.io/lil-log/assets/images/encoder-decoder-attention.png&quot; alt=&quot;&quot; /&gt;

&lt;center&gt;
    The encoder-decoder model with additive attention mechanism in [Bahdanau et al., 2015](https://arxiv.org/pdf/1409.0473.pdf).
&lt;/center&gt;

X为输入序列，y为预测序列，我们可以看到这个双向RNN的所有隐藏层输出被一个权重向量$\alpha$加权结合起来了，不再像以前一样，只使用最后一个隐藏层的输出：
&lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
% &lt;![CDATA[
\begin{aligned}
\boldsymbol{h}_i &amp;= [\overrightarrow{\boldsymbol{h}}_i^\top; \overleftarrow{\boldsymbol{h}}_i^\top]^\top, i=1,\dots,n\\
\mathbf{c}_t &amp;= \sum_{i=1}^n \alpha_{t,i} \boldsymbol{h}_i &amp; \small{\text{; Context vector for output }y_t}\\
\alpha_{t,i} &amp;= \text{align}(y_t, x_i) &amp; \small{\text{; How well two words }y_t\text{ and }x_i\text{ are aligned.}}\\
&amp;= \frac{\exp(\text{score}(\boldsymbol{s}_{t-1}, \boldsymbol{h}_i))}{\sum_{i'=1}^n \exp(\text{score}(\boldsymbol{s}_{t-1}, \boldsymbol{h}_{i'}))} &amp; \small{\text{; Softmax of some predefined alignment score.}}.
\end{aligned} %]]&gt; %]]&gt;&lt;/script&gt;

&lt;blockquote&gt;
  The &lt;img src=&quot;http://s0.wp.com/latex.php?zoom=1.3802082538604736&amp;amp;latex=a%27s&amp;amp;bg=ffffff&amp;amp;fg=000&amp;amp;s=0&quot; alt=&quot;a's&quot; /&gt; are typically normalized to sum to 1 (so they are a distribution over the input states)
&lt;/blockquote&gt;

这个$\alpha$是一个矩阵，第t行($t=1……n$)表示$h_1,……,h_n$对$y_t$的输出所作的贡献，也就是说在decoder中，$y_{t-1}$和$\sum_{i=1}^n \alpha_{t,i} \boldsymbol{h}_i $作为t时刻Decoder的输入。

在这篇文章中，$\alpha$如何得到呢？通过一个单层隐藏层学得,$t$时刻$h_i$对$s_t$ or $y_t$的作用分数为：
&lt;script type=&quot;math/tex&quot;&gt;\text{score}(\boldsymbol{s}_t, \boldsymbol{h}_i) = \mathbf{v}_a^\top \tanh(\mathbf{W}_a[\boldsymbol{s}_t; \boldsymbol{h}_i])&lt;/script&gt;
$V^T_a$和$W_a$都是待学习参数。以下就是学得的作用关系图，越亮，表示输入$x_i$对输出$y_j$的作用越大：

&lt;img src=&quot;https://lilianweng.github.io/lil-log/assets/images/bahdanau-fig3.png&quot; alt=&quot;&quot; /&gt;

&lt;center&gt;
     Alignment matrix of “L’accord sur l’Espace économique européen a été signé en août 1992” (French) and its English translation “The agreement on the European Economic Area was signed in August 1992”. (Image source: Fig 3 in Bahdanau et al., 2015)
&lt;/center&gt;

&lt;h3 id=&quot;attention-or-memory&quot;&gt;Attention or Memory&lt;/h3&gt;

引入attention往往会引入新的计算代价，比如说处理上百的token sequence时，每个timestep输出的是h-dim的，那就会增加很多计算量：

&lt;blockquote&gt;
  Actually, that’s quite counterintuitive. Human attention is something that’s supposed to &lt;strong&gt;save&lt;/strong&gt;computational resources. By focusing on one thing, we can neglect many other things. But that’s not really what we’re doing in the above model. We’re essentially looking at everything in detail before deciding what to focus on. Intuitively that’s equivalent outputting a translated word, and then going back through &lt;em&gt;all&lt;/em&gt; of your internal memory of the text in order to decide which word to produce next. That seems like a waste, and not at all what humans are doing. In fact, &lt;strong&gt;&lt;u&gt;it’s more akin to memory access,&lt;/u&gt;&lt;/strong&gt;In this interpretation, instead of choosing what to “attend” to, the network chooses what to retrieve from memory.  not attention, which in my opinion is somewhat of a misnomer (more on that below). Still, that hasn’t stopped attention mechanisms from becoming quite popular and performing well on many tasks.

  An alternative approach to attention is to use Reinforcement Learning to predict an approximate location to focus to. That sounds a lot more like human attention, and that’s what’s done in &lt;a href=&quot;http://arxiv.org/abs/1406.6247&quot;&gt;Recurrent Models of Visual Attention&lt;/a&gt;.

  Memory Mechanisms themselves have a much longer history……
&lt;/blockquote&gt;

&lt;h3 id=&quot;attention-family&quot;&gt;Attention Family&lt;/h3&gt;

With the help of the attention, the dependencies between source and target sequences are not restricted by the in-between distance anymore! Given the big improvement by attention in machine translation, it soon got extended into the computer vision field (&lt;a href=&quot;http://proceedings.mlr.press/v37/xuc15.pdf&quot;&gt;Xu et al. 2015&lt;/a&gt;) and people started exploring various other forms of attention mechanisms (&lt;a href=&quot;https://arxiv.org/pdf/1508.04025.pdf&quot;&gt;Luong, et al., 2015&lt;/a&gt;; &lt;a href=&quot;https://arxiv.org/abs/1703.03906&quot;&gt;Britz et al., 2017&lt;/a&gt;; &lt;a href=&quot;http://papers.nips.cc/paper/7181-attention-is-all-you-need.pdf&quot;&gt;Vaswani, et al., 2017&lt;/a&gt;).

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Name&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Alignment score function&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Citation&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;Content-base attention&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;$\text{score}(\boldsymbol{s}_t, \boldsymbol{h}_i) = \text{cosine}[\boldsymbol{s}_t, \boldsymbol{h}_i]$&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;a href=&quot;https://arxiv.org/abs/1410.5401&quot;&gt;Graves2014&lt;/a&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;Additive(*)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;$\text{score}(\boldsymbol{s}_t, \boldsymbol{h}_i) = \mathbf{v}_a^\top \tanh(\mathbf{W}_a[\boldsymbol{s}_t; \boldsymbol{h}_i])$&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;a href=&quot;https://arxiv.org/pdf/1409.0473.pdf&quot;&gt;Bahdanau2015&lt;/a&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;Location-Base&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;$\alpha_{t,i} = \text{softmax}(\mathbf{W}_a \boldsymbol{s}_t)$&lt;br /&gt;Note: This simplifies the softmax alignment to only depend on the target position.&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;a href=&quot;https://arxiv.org/pdf/1508.04025.pdf&quot;&gt;Luong2015&lt;/a&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;General&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;$\text{score}(\boldsymbol{s}_t, \boldsymbol{h}_i) = \boldsymbol{s}_t^\top\mathbf{W}_a\boldsymbol{h}_i$&lt;br /&gt;where $W_a$ is a trainable weight matrix in the attention layer.&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;a href=&quot;https://arxiv.org/pdf/1508.04025.pdf&quot;&gt;Luong2015&lt;/a&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;Dot-Product&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;$\text{score}(\boldsymbol{s}_t, \boldsymbol{h}_i) = \boldsymbol{s}_t^\top\boldsymbol{h}_i$&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;a href=&quot;https://arxiv.org/pdf/1508.4025.pdf&quot;&gt;Luong2015&lt;/a&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;Scaled Dot-Product(^)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;$\text{score}(\boldsymbol{s}_t, \boldsymbol{h}_i) = \frac{\boldsymbol{s}_t^\top\boldsymbol{h}_i}{\sqrt{n}}$&lt;br /&gt;Note: very similar to the dot-product attention except for a scaling factor; where n is the dimension of the source hidden state.&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt; &lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

(*) Referred to as “concat” in Luong, et al., 2015 and as “additive attention” in Vaswani, et al., 2017.
(^) It adds a scaling factor $1/\sqrt{n}$, motivated by the concern when the input is large, the softmax function may have an extremely small gradient, hard for efficient learning.

&lt;h4 id=&quot;attention分类&quot;&gt;Attention分类&lt;/h4&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Name&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Definition&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Citation&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;Self-Attention(&amp;amp;)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;Relating different positions of the same input sequence. Theoretically the self-attention can adopt any score functions above, but just replace the target sequence with the same input sequence.&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;a href=&quot;https://arxiv.org/pdf/1601.06733.pdf&quot;&gt;Cheng2016&lt;/a&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;Global/Soft&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;Attending to the entire input state space.&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;a href=&quot;http://proceedings.mlr.press/v37/xuc15.pdf&quot;&gt;Xu2015&lt;/a&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;Local/Hard&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;Attending to the part of input state space; i.e. a patch of the input image.&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;a href=&quot;http://proceedings.mlr.press/v37/xuc15.pdf&quot;&gt;Xu2015&lt;/a&gt;; &lt;a href=&quot;https://arxiv.org/pdf/1508.04025.pdf&quot;&gt;Luong2015&lt;/a&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

(&amp;amp;) Also, referred to as “&lt;strong&gt;intra-attention&lt;/strong&gt;” in Cheng et al., 2016 and some other papers.

接下来具体讲一些详细的Attention

&lt;h4 id=&quot;self-attention&quot;&gt;Self-Attention&lt;/h4&gt;

也叫intra-attention，在机器阅读、文章摘要、图像描述生成等领域很有用，也就是在同一个句子里面进行不同位置的attention，以在句子内部产生一个关联性信息的表达。

&lt;h4 id=&quot;soft-vs-hard-attention&quot;&gt;Soft vs Hard Attention&lt;/h4&gt;

在 &lt;a href=&quot;http://proceedings.mlr.press/v37/xuc15.pdf&quot;&gt;show, attend and tell&lt;/a&gt; 这篇文章中，提出soft\hard两种attention，不同在于两种attention所获取的信息不同，soft attention关注整张图像，而hard attention则关注图像部分区域，两者各有优势和劣势：

&lt;ul&gt;
  &lt;li&gt;soft：
    &lt;ul&gt;
      &lt;li&gt;优点：模型平滑、可微&lt;/li&gt;
      &lt;li&gt;缺点：当输入较大时，计算量大；&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;hard
    &lt;ul&gt;
      &lt;li&gt;优势：在测试阶段计算量小&lt;/li&gt;
      &lt;li&gt;劣势：不可微，需要借助variance reduction 或 reinforcement learning来训练&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;global-vs-local-attention&quot;&gt;Global vs. Local Attention&lt;/h4&gt;

&lt;a href=&quot;https://arxiv.org/pdf/1508.04025.pdf&quot;&gt;Luong, et al., 2015&lt;/a&gt;提出了两种attention，global attention类似于soft attention，而local attention是hard attentiond和soft attention的协调，它是可微的：

&lt;blockquote&gt;
  the model first predicts a single aligned position for the current target word and a window centered around the source position is then used to compute a context vector.
&lt;/blockquote&gt;

&lt;img src=&quot;https://lilianweng.github.io/lil-log/assets/images/luong2015-fig2-3.png&quot; alt=&quot;&quot; /&gt;

&lt;center&gt;
     Global vs local attention (Image source: Fig 2 &amp;amp; 3 in Luong, et al., 2015)
&lt;/center&gt;

&lt;h2 id=&quot;nmt&quot;&gt;NMT&lt;/h2&gt;

在介绍Transformer之前，我们介绍下NMT(Neural Turing Machines)。先来看下对Turing Machine的定义：

&lt;blockquote&gt;
  Alan Turing in &lt;a href=&quot;https://en.wikipedia.org/wiki/Turing_machine&quot;&gt;1936&lt;/a&gt; proposed a minimalistic model of computation. It is composed of a infinitely long tape and a head to interact with the tape. The tape has countless cells on it, each filled with a symbol: 0, 1 or blank (“ “). The operation head can read symbols, edit symbols and move left/right on the tape. Theoretically a Turing machine can simulate any computer algorithm, irrespective of how complex or expensive the procedure might be. The infinite memory gives a Turing machine an edge to be mathematically limitless. However, infinite memory is not feasible in real modern computers and then we only consider Turing machine as a mathematical model of computation.

  &lt;img src=&quot;https://lilianweng.github.io/lil-log/assets/images/turing-machine.jpg&quot; alt=&quot;turing-machine&quot; /&gt;

  &lt;em&gt;Fig. 9. How a Turing machine looks like: a tape + a head that handles the tape. (Image source: http://aturingmachine.com/)&lt;/em&gt;
&lt;/blockquote&gt;

再看下NTM的定义：

&lt;blockquote&gt;
  &lt;strong&gt;Neural Turing Machine&lt;/strong&gt; (&lt;strong&gt;NTM&lt;/strong&gt;, &lt;a href=&quot;https://arxiv.org/abs/1410.5401&quot;&gt;Graves, Wayne &amp;amp; Danihelka, 2014&lt;/a&gt;) is a model architecture for coupling a neural network with external memory storage. The memory mimics the Turing machine tape and the neural network controls the operation heads to read from or write to the tape. However, the memory in NTM is finite, and thus it probably looks more like a “Neural &lt;a href=&quot;https://en.wikipedia.org/wiki/Von_Neumann_architecture&quot;&gt;von Neumann&lt;/a&gt; Machine”.
&lt;/blockquote&gt;

NTM包含一个Controller和一个memory bank。前者可以是任何形式的神经网络，后者则是$N×M$的存储矩阵。Controller在处理操作的时候并行的访问memory，所有的读取写入操作都是结合soft attention进行的，也就是说都读或写的数据加上权重。

&lt;img src=&quot;https://lilianweng.github.io/lil-log/assets/images/NTM.png&quot; alt=&quot;turing-machine&quot; /&gt;

&lt;em&gt;Fig 10. Neural Turing Machine Architecture.&lt;/em&gt;

&lt;h4 id=&quot;读写操作&quot;&gt;读写操作&lt;/h4&gt;

读取时，权重$w_t$控制对内存内容的行赋予权重：
&lt;script type=&quot;math/tex&quot;&gt;\mathbf{r}_i = \sum_{i=1}^N w_t(i)\mathbf{M}_t(i)\text{, where }\sum_{i=1}^N w_t(i)=1, \forall i: 0 \leq w_t(i) \leq 1&lt;/script&gt;
$w_t(i)$为第i个权重,$M_t(i)$为第i行内存向量。

写入时：
&lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
% &lt;![CDATA[
\begin{aligned}
\tilde{\mathbf{M}}_t(i) &amp;= \mathbf{M}_{t-1}(i) [\mathbf{1} - w_t(i)\mathbf{e}_t] &amp;\scriptstyle{\text{; erase}}\\
\mathbf{M}_t(i) &amp;= \tilde{\mathbf{M}}_t(i) + w_t(i) \mathbf{a}_t &amp;\scriptstyle{\text{; add}}
\end{aligned} %]]&gt; %]]&gt;&lt;/script&gt;

&lt;h4 id=&quot;attention机制&quot;&gt;Attention机制&lt;/h4&gt;

如何产生$w_t$呢？NTM使用了混合的 content-based 和location-based addressings。

&lt;h5 id=&quot;content-based-addressing&quot;&gt;Content-based addressing&lt;/h5&gt;

Controller从input获得key vector $k_t$,计算它和memory row的cosine相似性,然后通过softmax进行归一化，另外引入$\beta_t$来放大或者缩小分布的关注重点：
&lt;script type=&quot;math/tex&quot;&gt;w_t^c(i) 
= \text{softmax}(\beta_t \cdot \text{cosine}[\mathbf{k}_t, \mathbf{M}_t(i)])
= \frac{\exp(\beta_t \frac{\mathbf{k}_t \cdot \mathbf{M}_t(i)}{\|\mathbf{k}_t\| \cdot \|\mathbf{M}_t(i)\|})}{\sum_{j=1}^N \exp(\beta_t \frac{\mathbf{k}_t \cdot \mathbf{M}_t(j)}{\|\mathbf{k}_t\| \cdot \|\mathbf{M}_t(j)\|})}&lt;/script&gt;

&lt;h5 id=&quot;interpolation&quot;&gt;Interpolation&lt;/h5&gt;

计算了上步中的attention之后，我们结合上个timestep所产生的的 content-based attention计算最终的 content-based attention：
&lt;script type=&quot;math/tex&quot;&gt;\mathbf{w}_t^g = g_t \mathbf{w}_t^c + (1 - g_t) \mathbf{w}_{t-1}&lt;/script&gt;

&lt;h5 id=&quot;location-based-addressing&quot;&gt;Location-based addressing&lt;/h5&gt;

location-based addressing就是将attention vector中不同位置的值加权起来，具体就是通过&lt;u&gt;允许整数移位的加权分布(a weighting distribution over allowable integer shifts)&lt;/u&gt;进行加权,它等价于卷积核(关于位置的偏移)为$s_t(·)$的一维卷积，有很多方式来定义这个分布：

&lt;img src=&quot;https://lilianweng.github.io/lil-log/assets/images/shift-weighting.png&quot; alt=&quot;shift-weighting&quot; /&gt;

&lt;center&gt;
    Two ways to represent the shift weighting distribution stst.
&lt;/center&gt;

最终的attention经过$\gamma_t\ge1$来加强锐化：
&lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
% &lt;![CDATA[
\begin{aligned}
\tilde{w}_t(i) &amp;= \sum_{j=1}^N w_t^g(j) s_t(i-j) &amp; \scriptstyle{\text{; circular convolution}}\\
w_t(i) &amp;= \frac{\tilde{w}_t(i)^{\gamma_t}}{\sum_{j=1}^N \tilde{w}_t(j)^{\gamma_t}} &amp; \scriptstyle{\text{; sharpen}}
\end{aligned} %]]&gt; %]]&gt;&lt;/script&gt;
整个产生$w_t$的过程如下所示,如果有并行的read和write操作，则controller将产生多组输出：

&lt;img src=&quot;https://lilianweng.github.io/lil-log/assets/images/NTM-flow-addressing.png&quot; alt=&quot;NTM-flow-addressing&quot; /&gt;

&lt;center&gt;
    Fig. 12. Flow diagram of the addressing mechanisms in Neural Turing Machine. (Image source: Graves, Wayne &amp;amp; Danihelka, 2014)
&lt;/center&gt;

&lt;h2 id=&quot;transformer&quot;&gt;Transformer&lt;/h2&gt;

Transformer是&lt;a href=&quot;http://papers.nips.cc/paper/7181-attention-is-all-you-need.pdf&quot;&gt;“Attention is All you Need”&lt;/a&gt; (Vaswani, et al., 2017)提出的一中soft attention，它使得不使用RNN units进行seq2seq的任务解决成为可能，Transformer模型完全建立在self-attention机制之上，并使用sequence-aligned recurrent architecture。这个模型最初是为了提高机器翻译的效率，因为RNN是顺序执行的，t时刻没有完成就不能处理t+1时刻，因此很难并行，但Transformer的Self-Attention机制和Position Encoding可以替代RNN，从而实现效率。后来发现Self-Attention效果很好，在很多其它的地方也可以使用Transformer模型。这包括著名的OpenAI GPT和BERT模型，都是以Transformer为基础的。当然它们只使用了Transformer的Decoder部分，由于没有了Encoder，Decoder只有Self-Attention而没有普通的Attention。

&lt;h4 id=&quot;key-value-and-query&quot;&gt;Key, Value and Query&lt;/h4&gt;

主要组件是&lt;em&gt;multi-head self-attention mechanism&lt;/em&gt;部分，它将输入和其编码表达看成key-value（K-V）对，且维度都是序列长度$n$。根据神经机器翻译的思想，(K,V)就是encoder 的隐藏状态；上一个输出被压缩成一个query(Q, m-dim),那么下一个输出，其实就是对(K,V,Q)的一个映射。

这里使用的attention是 前面表中scaled dot-product attention，针对V进行加权：
&lt;script type=&quot;math/tex&quot;&gt;\text{Attention}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \text{softmax}(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{n}})\mathbf{V}&lt;/script&gt;

&lt;h4 id=&quot;multi-head-self-attention&quot;&gt;Multi-Head Self-Attention&lt;/h4&gt;

&lt;img src=&quot;https://lilianweng.github.io/lil-log/assets/images/multi-head-attention.png&quot; alt=&quot;multi-head scaled dot-product attention&quot; /&gt;

&lt;center&gt;
    Fig. 14. Multi-head scaled dot-product attention mechanism. (Image source: Fig 2 in Vaswani, et al., 2017)
&lt;/center&gt;

主要思想就是并行的运行这个scaled dot-product attention多次，然后拼接之后通过线性变换获取最终的attention，根据论文描述：

&lt;blockquote&gt;
  “multi-head attention allows the model to jointly attend to information from different representation &lt;strong&gt;subspaces&lt;/strong&gt; at different positions. With a single attention head, averaging inhibits this.”
&lt;/blockquote&gt;

公式为：
&lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
% &lt;![CDATA[
\begin{aligned}
\text{MultiHead}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) &amp;= [\text{head}_1; \dots; \text{head}_h]\mathbf{W}^O \\
\text{where head}_i &amp;= \text{Attention}(\mathbf{Q}\mathbf{W}^Q_i, \mathbf{K}\mathbf{W}^K_i, \mathbf{V}\mathbf{W}^V_i)
\end{aligned} %]]&gt; %]]&gt;&lt;/script&gt;
$W_i^Q,W_i^K,W_i^V,W^O$都是需要学习的参数。

&lt;h4 id=&quot;encoder&quot;&gt;Encoder&lt;/h4&gt;

&lt;img src=&quot;https://lilianweng.github.io/lil-log/assets/images/transformer-encoder.png&quot; alt=&quot;Transformer encoder&quot; /&gt;

&lt;center&gt;
    Fig. 15. The transformer’s encoder. (Image source: Vaswani, et al., 2017)
&lt;/center&gt;

encoder产生attention-based表示

&lt;ul&gt;
  &lt;li&gt;6个等同的层&lt;/li&gt;
  &lt;li&gt;每层有一个&lt;strong&gt;multi-head self-attention layer&lt;/strong&gt;和一个全连接层(feed forward)&lt;/li&gt;
  &lt;li&gt;每个子层都采用残差链接，以及层归一化操作，输出维度均为512-dim&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;decoder&quot;&gt;Decoder&lt;/h4&gt;

&lt;img src=&quot;https://lilianweng.github.io/lil-log/assets/images/transformer-decoder.png&quot; alt=&quot;&quot; /&gt;

&lt;center&gt;
    The transformer’s decoder. (Image source: Vaswani, et al., 2017)
&lt;/center&gt;

decoder通过使用context的信息，恢复或者产生想要的东西，结构描述：

&lt;ul&gt;
  &lt;li&gt;
    6个等同层
  &lt;/li&gt;
  &lt;li&gt;
    每层两个子层，都使用multi-head self-attention layer，其中一个子层连接着一个全连接层
  &lt;/li&gt;
  &lt;li&gt;
    子层都有残差连接以及归一化操作
  &lt;/li&gt;
  &lt;li&gt;
    每层的第一个multi-head self-attention layer加了mask

    &lt;blockquote&gt;
      The first multi-head attention sub-layer is &lt;strong&gt;modified&lt;/strong&gt; to prevent positions from attending to subsequent positions, as we don’t want to look into the future of the target sequence when predicting the current position.
    &lt;/blockquote&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;整个transformer结构&quot;&gt;整个Transformer结构&lt;/h4&gt;

&lt;img src=&quot;https://lilianweng.github.io/lil-log/assets/images/transformer.png&quot; alt=&quot;&quot; /&gt;

&lt;center&gt;
    The full model architecture of the transformer. (Image source: Fig 1 &amp;amp; 2 in Vaswani, et al., 2017.)
&lt;/center&gt;

&lt;h2 id=&quot;referrence&quot;&gt;Referrence&lt;/h2&gt;

感谢下面的文章博客等，文章有些部分是中英文混合的，一个原因是怕翻译不正确，另一个原因是内容太多，偷了点懒……

https://lilianweng.github.io/lil-log/2018/06/24/attention-attention.html#summary

https://towardsdatascience.com/understanding-encoder-decoder-sequence-to-sequence-model-679e04af4346

https://arxiv.org/pdf/1409.3215.pdf?source=post_page—————————

&lt;a href=&quot;https://caicai.science/2018/10/06/attention总览/&quot;&gt;https://caicai.science/2018/10/06/attention%E6%80%BB%E8%A7%88/&lt;/a&gt;

http://www.wildml.com/2016/01/attention-and-memory-in-deep-learning-and-nlp/?source=post_page—————————
</description>
        <pubDate>Fri, 28 Jun 2019 17:40:41 +0000</pubDate>
        <link>https://narcissuscyn.github.io/2019/06/28/transformer/</link>
        <guid isPermaLink="true">https://narcissuscyn.github.io/2019/06/28/transformer/</guid>
        
        
        <category>NLP</category>
        
      </item>
    
      <item>
        <title>十大排序算法(一)-堆排序</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#理解&quot; id=&quot;markdown-toc-理解&quot;&gt;理解&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#堆的概念&quot; id=&quot;markdown-toc-堆的概念&quot;&gt;堆的概念：&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#堆排序&quot; id=&quot;markdown-toc-堆排序&quot;&gt;堆排序&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#基本操作&quot; id=&quot;markdown-toc-基本操作&quot;&gt;基本操作&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#性质&quot; id=&quot;markdown-toc-性质&quot;&gt;性质&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#原理&quot; id=&quot;markdown-toc-原理&quot;&gt;原理&lt;/a&gt;            &lt;ul&gt;
              &lt;li&gt;&lt;a href=&quot;#基本操作-1&quot; id=&quot;markdown-toc-基本操作-1&quot;&gt;基本操作&lt;/a&gt;                &lt;ul&gt;
                  &lt;li&gt;&lt;a href=&quot;#第一步build-构建最大堆&quot; id=&quot;markdown-toc-第一步build-构建最大堆&quot;&gt;第一步：build-构建最大堆&lt;/a&gt;&lt;/li&gt;
                  &lt;li&gt;&lt;a href=&quot;#堆的插入和删除操作&quot; id=&quot;markdown-toc-堆的插入和删除操作&quot;&gt;堆的插入和删除操作&lt;/a&gt;&lt;/li&gt;
                &lt;/ul&gt;
              &lt;/li&gt;
            &lt;/ul&gt;
          &lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#堆排序实现&quot; id=&quot;markdown-toc-堆排序实现&quot;&gt;堆排序实现&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#基类&quot; id=&quot;markdown-toc-基类&quot;&gt;基类&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#最大堆&quot; id=&quot;markdown-toc-最大堆&quot;&gt;最大堆&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#头文件&quot; id=&quot;markdown-toc-头文件&quot;&gt;头文件&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#cpp文件&quot; id=&quot;markdown-toc-cpp文件&quot;&gt;cpp文件&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;理解&quot;&gt;理解&lt;/h2&gt;
堆分为最大堆和最小堆，这里以最大堆为例子进行讲解。
&lt;img src=&quot;https://narcissuspicbed.oss-cn-hangzhou.aliyuncs.com/media/15481443735185/15482302030972.png&quot; alt=&quot;&quot; /&gt;

&lt;h3 id=&quot;堆的概念&quot;&gt;堆的概念：&lt;/h3&gt;
&lt;blockquote&gt;
  堆（英语：Heap）是计算机科学中的一种特别的树状数据结构。若是满足以下特性，即可称为堆：“给定堆中任意节点 P 和 C，若 P 是 C 的母节点，那么 P 的值会小于等于（或大于等于） C 的值”。若母节点的值恒小于等于子节点的值，此堆称为最小堆（英语：min heap）；反之，若母节点的值恒大于等于子节点的值，此堆称为最大堆（英语：max heap）。在堆中最顶端的那一个节点，称作根节点（英语：root node），根节点本身没有母节点（英语：parent node）。

  n个元素序列${k_1, k_2… k_i…k_n}$,当且仅当满足下列关系时称之为堆：
$(k_i &amp;lt;= k_{2i}, k_i &amp;lt;= k_{2i+1)}$或者$(k_i &amp;gt;= k_{2i}, k_i &amp;gt;= k_{2i+1}), (i = 1, 2, 3, 4… n/2)$
&lt;/blockquote&gt;

&lt;blockquote&gt;
  在队列中，调度程序反复提取队列中第一个作业并运行，因为实际情况中某些时间较短的任务将等待很长时间才能结束，或者某些不短小，但具有重要性的作业，同样应当具有优先权。堆即为解决此类问题设计的一种数据结构。[1] 
~维基百科
&lt;/blockquote&gt;

&lt;h3 id=&quot;堆排序&quot;&gt;堆排序&lt;/h3&gt;
&lt;h4 id=&quot;基本操作&quot;&gt;基本操作&lt;/h4&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;操作&lt;/th&gt;
      &lt;th&gt;描述&lt;/th&gt;
      &lt;th&gt;时间复杂度&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;build&lt;/td&gt;
      &lt;td&gt;创建一个空堆&lt;/td&gt;
      &lt;td&gt;$O(n)$&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;insert&lt;/td&gt;
      &lt;td&gt;向堆中插入一个新元素&lt;/td&gt;
      &lt;td&gt;$O(log n)$&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;get&lt;/td&gt;
      &lt;td&gt;获取当前堆顶元素的值&lt;/td&gt;
      &lt;td&gt;$O(1)$&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;delete&lt;/td&gt;
      &lt;td&gt;删除堆顶元素&lt;/td&gt;
      &lt;td&gt;$O(\log n) $&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h4 id=&quot;性质&quot;&gt;性质&lt;/h4&gt;
&lt;img src=&quot;https://narcissuspicbed.oss-cn-hangzhou.aliyuncs.com/media/15481443735185/15482302266450.png&quot; alt=&quot;&quot; /&gt;

堆一般用数组或者vector来存储，通过索引的操作虚拟一个&lt;strong&gt;完全二叉树&lt;/strong&gt;结构。其性质有：
&lt;ul&gt;
  &lt;li&gt;任意节点小于（或大于）它的所有后裔，最小元（或最大元）在堆的根上（堆序性）。&lt;/li&gt;
  &lt;li&gt;堆总是一棵&lt;strong&gt;完全树&lt;/strong&gt;。即除了最底层，其他层的节点都被元素填满，且最底层尽可能地从左到右填入。&lt;/li&gt;
&lt;/ul&gt;

常见的堆有二叉堆、斐波那契堆等。

&lt;h4 id=&quot;原理&quot;&gt;原理&lt;/h4&gt;
虽然理论容易理解，但是要真正把这个算法搞通，包括能直接手写算法，在实现的时候还是会觉得有一点难度。这里需要谨记的是 &lt;em&gt;&lt;strong&gt;给定一个根节点， 若其左子树和右子树同时满足堆的条件后，对根节点完成下沉操作后，整个树🌲一定是一个堆。&lt;/strong&gt;&lt;/em&gt;

&lt;strong&gt;完全二叉树的节点索引关系&lt;/strong&gt;
假设有一个数组从1开始的size为n的数组arr。其最后一个非叶子节点的索引为$start=(n/2)$,该非叶子节点的左儿子为$start&lt;em&gt;2$,右儿子为$start&lt;/em&gt;2+1$;注意，若数组从0开始，其最后一个非叶子节点的索引为$start=(n/2-1)$,该非叶子节点的左儿子为$start&lt;em&gt;2+1$,右儿子为$start&lt;/em&gt;2+2$，以下部分，包括实现，都是从0开始的。

&lt;h5 id=&quot;基本操作-1&quot;&gt;基本操作&lt;/h5&gt;
这里只解说，几个比较难的操作。
&lt;h6 id=&quot;第一步build-构建最大堆&quot;&gt;第一步：build-构建最大堆&lt;/h6&gt;
给定一个输入数组，可以得到如下的一个初始完全二叉树
&lt;img src=&quot;https://narcissuspicbed.oss-cn-hangzhou.aliyuncs.com/media/15481443735185/15482312384981.png&quot; alt=&quot;&quot; /&gt;
为了得到一个堆，build操作需要从这个二叉树的最后一个非叶子节点开始，对所有的非叶子节点进行下沉操作,也就是MaxHeap构造函数中下面的代码：

&lt;div class=&quot;language-c++ highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;curPos&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//最后一个非叶子节点
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;curPos&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//循环下沉所有叶子节点
&lt;/span&gt;    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;shift_down&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;curPos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;arrSize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//下沉操作
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;curPos&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//非叶子节点的位置
&lt;/span&gt;    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
最终得到这样一个堆：
&lt;img src=&quot;https://narcissuspicbed.oss-cn-hangzhou.aliyuncs.com/media/15481443735185/15482316323218.png&quot; alt=&quot;&quot; /&gt;

&lt;strong&gt;下沉&lt;/strong&gt;
这个地方需要讲解一下下沉操作。下沉每个节点的时候，都要保证其做子树和右子树都是一个堆，这也是为什么构建堆时，下沉操作是从最后一个非叶子节点开始的。我们再回忆前面的关键概念：给定一个树的根节点， 若其左子树和右子树同时满足堆的条件后，对根节点完成下沉操作后，整个树🌲一定是一个堆。

下沉操作是通过一个循环来实现的，循环是为了保证下沉能够完全进行，也就是说有可能下沉一次，交换了两个节点的值，会导致子树不再满足堆的性质，这个时候，这个节点还需要继续下沉。也就是下面的例子：4要下沉两次。
&lt;img src=&quot;https://narcissuspicbed.oss-cn-hangzhou.aliyuncs.com/media/15481443735185/15482320745086.png&quot; alt=&quot;&quot; /&gt;
&lt;img src=&quot;media/15481443735185/15482320884522.png&quot; alt=&quot;&quot; /&gt;

&lt;div class=&quot;language-c++ highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;  &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;temp&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//当前非叶子节点
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//是否继续进行往下沉的条件
&lt;/span&gt;    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;end&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//找到两个儿子节点更大的一个
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;temp&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//表示此节点i已经满足堆的条件，不需要继续往下沉；
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;//否则，会继续往下判断
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//新的节点
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//新节点的左子节点
&lt;/span&gt;    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;temp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//完成两个节点的交换，也可能是heap[i]和自身的赋值,比如在while循环的第一遍循环就break出去。
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
这个地方还需要注意的是对新的非叶子节点索引的计算以及左儿子索引非计算。

&lt;h6 id=&quot;堆的插入和删除操作&quot;&gt;堆的插入和删除操作&lt;/h6&gt;
堆构建完成后，我们可以进行插入和删除操作，插入操作的思想就是讲元素插入到堆的末尾，也就是数组的末尾，堆的尺寸加1，然后对这个末尾的新元素进行上浮操作，也就是说一直向上移动该元素，直到其父节点大于该元素。若插入&lt;strong&gt;前&lt;/strong&gt;，该数组的大小为size，那么新元素的父节点索引就是$i=(size-1)/2$,若一次上浮无法满足堆的性质，就计算新的父节点i=$(i-1)/2$。
&lt;div class=&quot;language-c++ highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;    &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;temp&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;temp&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//插入的时候就已经满足堆的条件,则不需要再继续上浮了
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//插入时不满足，上浮
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//j指向其父节点
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//j为新j的父节点
&lt;/span&gt;    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;temp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//完成交换
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

对于删除操作呢，就比较简单了，就是交换堆顶元素和最后一个元素的值，堆的尺寸减1，然后对根节点进行下沉操作即可，因为我们要时刻记得：给定一个树的根节点， 若其左子树和右子树同时满足堆的条件后，对根节点完成&lt;strong&gt;下沉&lt;/strong&gt;操作后，整个树🌲一定是一个堆。所以删除操作就没有什么复杂的操作了。

&lt;h2 id=&quot;堆排序实现&quot;&gt;堆排序实现&lt;/h2&gt;
要注意空堆和堆容量的判断，还有堆的尺寸要注意改变。
&lt;h3 id=&quot;基类&quot;&gt;基类&lt;/h3&gt;
&lt;div class=&quot;language-c++ highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cp&quot;&gt;#ifndef SORT_HEAP_H
#define SORT_HEAP_H
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;enum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DEFAUKT_SIZE&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;};&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;template&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;typename&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Heap&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;public&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;Heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;default&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;virtual&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;~&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;default&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;virtual&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;show_heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;virtual&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;bool&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;insert_heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;virtual&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;bool&lt;/span&gt;  &lt;span class=&quot;n&quot;&gt;remove_heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;};&lt;/span&gt;
&lt;span class=&quot;cp&quot;&gt;#endif //SORT_HEAP_H
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;h3 id=&quot;最大堆&quot;&gt;最大堆&lt;/h3&gt;
&lt;h4 id=&quot;头文件&quot;&gt;头文件&lt;/h4&gt;
&lt;div class=&quot;language-c++ highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cp&quot;&gt;#ifndef SORT_MAXHEAP_H
#define SORT_MAXHEAP_H
&lt;/span&gt;
&lt;span class=&quot;cp&quot;&gt;#include &quot;heap.h&quot;
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;template&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;typename&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MaxHeap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Heap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;public&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;cm&quot;&gt;/**
     * 创建一个空堆
     */&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;MaxHeap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sz&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DEFAUKT_SIZE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;cm&quot;&gt;/**
     * 根据已有数组堆创建一个堆
     */&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;MaxHeap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[],&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;cm&quot;&gt;/**
     * 析构函数
     */&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;~&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;MaxHeap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt;
    &lt;span class=&quot;cm&quot;&gt;/**
     * 显示堆
     */&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;show_heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;const&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;cm&quot;&gt;/**
     * 向堆中插入元素
     * @return
     */&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;bool&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;insert_heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;cm&quot;&gt;/**
     * 移除堆中的元素
     * @return
     */&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;bool&lt;/span&gt;  &lt;span class=&quot;n&quot;&gt;remove_heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;protected&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;cm&quot;&gt;/**
     * 下浮
     */&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shift_down&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;cm&quot;&gt;/**
     * 上浮
     */&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shift_up&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;private&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;//指向堆的指针
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;//已有堆中元素个数
&lt;/span&gt;    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;//堆的容量
&lt;/span&gt;    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;capacity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;};&lt;/span&gt;
&lt;span class=&quot;cp&quot;&gt;#endif //SORT_MAXHEAP_H
&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;h4 id=&quot;cpp文件&quot;&gt;cpp文件&lt;/h4&gt;
&lt;div class=&quot;language-c++ highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cp&quot;&gt;#include &amp;lt;form.h&amp;gt;
#include &quot;MaxHeap.h&quot;
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;template&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;typename&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;MaxHeap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;MaxHeap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sz&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;capacity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sz&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DEFAUKT_SIZE&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sz&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DEFAUKT_SIZE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;capacity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;assert&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;nullptr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;template&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;typename&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;MaxHeap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;MaxHeap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[],&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;arrSize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;capacity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;arrSize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DEFAUKT_SIZE&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;arrSize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DEFAUKT_SIZE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;capacity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;arrSize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;arrSize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;arr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;curPos&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;curPos&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;shift_down&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;curPos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;arrSize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;curPos&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;template&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;typename&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;MaxHeap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shift_down&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;start&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;start&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//第i个非叶子节点
&lt;/span&gt;    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;start&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//第i个非叶子节点的左儿子
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;temp&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//是否继续进行往下沉的条件
&lt;/span&gt;    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;end&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//找到两个儿子节点更大的一个
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;temp&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//表示此节点i已经满足堆的条件，不需要继续往下沉；
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;//否则，会继续往下判断
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//新的节点
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//新节点的左子节点
&lt;/span&gt;    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;temp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//完成两个节点的交换，也可能是heap[i]和自身的赋值,比如在while循环的第一遍循环就break出去。
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;template&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;typename&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;MaxHeap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;::~&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;MaxHeap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;delete&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;nullptr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;capacity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;template&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;typename&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;MaxHeap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shift_up&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;

    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//j为最后新加入的元素
&lt;/span&gt;    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//j的父节点
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;temp&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;temp&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//插入的时候就已经满足堆的条件
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//插入时不满足
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//j指向其父节点
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//j为新j的父节点
&lt;/span&gt;    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;temp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//完成交换
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;template&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;typename&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;bool&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;MaxHeap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;insert_heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;capacity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;shift_up&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;template&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;typename&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;bool&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;MaxHeap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;remove_heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;val&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;heap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
    &lt;span class=&quot;o&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;shift_down&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//这里root就是数组的第一个元素。
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;// 所以从0开始；而在初始建堆的时候是从最后一个非叶子节点开始下沉的，
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;// 这样是为了保证在下沉每个节点时，其左右子树都满足堆的条件。
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

参考资料：

&lt;a href=&quot;https://blog.csdn.net/FreeeLinux/article/details/52162788&quot;&gt;代码实现&lt;/a&gt;:https://blog.csdn.net/FreeeLinux/article/details/52162788

&lt;a href=&quot;https://www.cnblogs.com/chengxiao/p/6129630.html&quot;&gt;理论理解&lt;/a&gt;:https://www.cnblogs.com/chengxiao/p/6129630.html

</description>
        <pubDate>Wed, 23 Jan 2019 17:40:41 +0000</pubDate>
        <link>https://narcissuscyn.github.io/2019/01/23/%E5%A0%86%E6%8E%92%E5%BA%8F%E7%9A%84%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3/</link>
        <guid isPermaLink="true">https://narcissuscyn.github.io/2019/01/23/%E5%A0%86%E6%8E%92%E5%BA%8F%E7%9A%84%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3/</guid>
        
        <category>排序</category>
        
        
        <category>算法</category>
        
      </item>
    
      <item>
        <title>[转]论文阅读：Semi-Supervised Classification with Graph Convolutional Networks</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#思想&quot; id=&quot;markdown-toc-思想&quot;&gt;思想&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#特点&quot; id=&quot;markdown-toc-特点&quot;&gt;特点&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#symbols&quot; id=&quot;markdown-toc-symbols&quot;&gt;Symbols&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1 id=&quot;思想&quot;&gt;思想&lt;/h1&gt;
GCN 是&lt;strong&gt;谱图卷积&lt;/strong&gt;（spectral graph convolution） 的&lt;strong&gt;局部一阶近似&lt;/strong&gt;（localized first-order approximation）。GCN的另一个特点在于其&lt;strong&gt;模型规模会随图中边的数量的增长而线性增长&lt;/strong&gt;。总的来说，GCN 可以用于对&lt;strong&gt;局部图结构与节点特征&lt;/strong&gt;进行编码。
&lt;h1 id=&quot;特点&quot;&gt;特点&lt;/h1&gt;
图卷积神经网络具有几个特点：
&lt;ul&gt;
  &lt;li&gt;局部特性：图卷积神经网络关注的是图中以某节点为中心，K阶邻居之内的信息，这一点与GNN有本质的区别；&lt;/li&gt;
  &lt;li&gt;一阶特性：经过多种近似之后，GCN变成了一个一阶模型。也就是说，单层的GCN可以被用于处理图中一阶邻居上的信息；若要处理K阶邻居，可以采用多层GCN来实现；&lt;/li&gt;
  &lt;li&gt;参数共享：对于每个节点，其上的滤波器参数 W 是共享的，这也是其被称作图卷积网络的原因之一。
    &lt;h1 id=&quot;symbols&quot;&gt;Symbols&lt;/h1&gt;
  &lt;/li&gt;
  &lt;li&gt;$\mathcal{G}=(\mathcal{V},\mathcal{E}) $表示一个图， $\mathcal{V},\mathcal{E} $分别表示相应的节点集与边集，$u,v\in\mathcal{V} $表示图中的节点，$ (u,v)\in\mathcal{E} $表示图中的边。&lt;/li&gt;
  &lt;li&gt;A 表示图的&lt;strong&gt;邻接矩阵&lt;/strong&gt;（adjacency matrix）。节点的连接情况的矩阵。该矩阵可以是二值的，也可以是带权的&lt;/li&gt;
  &lt;li&gt;D 表示图的&lt;strong&gt;度矩阵&lt;/strong&gt;（degree matrix）。度矩阵是一个对角矩阵，对于&lt;strong&gt;无向图&lt;/strong&gt;来说，一般只使用入度矩阵或出度矩阵。&lt;/li&gt;
  &lt;li&gt;L 表示图的&lt;strong&gt;拉普拉斯矩阵&lt;/strong&gt;（Laplacian matrix），$\mathcal{L}$ 表示图的归一化拉普拉斯矩阵。
&lt;img src=&quot;media/15476964960097/15476970525903.jpg&quot; alt=&quot;-c&quot; /&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
        <pubDate>Thu, 17 Jan 2019 13:50:39 +0000</pubDate>
        <link>https://narcissuscyn.github.io/2019/01/17/GCN%E7%BB%8F%E5%85%B8%E8%AE%BA%E6%96%87/</link>
        <guid isPermaLink="true">https://narcissuscyn.github.io/2019/01/17/GCN%E7%BB%8F%E5%85%B8%E8%AE%BA%E6%96%87/</guid>
        
        <category>frameworks</category>
        
        
        <category>图像理解</category>
        
      </item>
    
      <item>
        <title>graph convolutional network思想简介</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#为什么有图卷积网络&quot; id=&quot;markdown-toc-为什么有图卷积网络&quot;&gt;为什么有图卷积网络&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

注：https://zhuanlan.zhihu.com/p/37091549，这篇blog写的很好，我借鉴其关键内容并重新整理了一下，添加了一些自己的看法。

&lt;h2 id=&quot;为什么有图卷积网络&quot;&gt;为什么有图卷积网络&lt;/h2&gt;

卷积神经网络的&lt;strong&gt;缺点&lt;/strong&gt;：它研究的对象还是限制在Euclidean domains的数据。什么是&lt;strong&gt;euclidean data&lt;/strong&gt;？ Euclidean data&lt;strong&gt;最显著的特征就是有规则的空间结构&lt;/strong&gt;，比如图片是规则的正方形栅格，比如语音是规则的一维序列。而&lt;strong&gt;这些数据结构能够用一维、二维的矩阵表示&lt;/strong&gt;，卷积神经网络处理起来很高效。

</description>
        <pubDate>Fri, 11 Jan 2019 17:40:41 +0000</pubDate>
        <link>https://narcissuscyn.github.io/2019/01/11/Gragh-convolutional-network/</link>
        <guid isPermaLink="true">https://narcissuscyn.github.io/2019/01/11/Gragh-convolutional-network/</guid>
        
        <category>frameworks</category>
        
        
        <category>图像理解</category>
        
      </item>
    
      <item>
        <title>0/1背包问题</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#01背包&quot; id=&quot;markdown-toc-01背包&quot;&gt;0/1背包&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#暴力解决二维动态规划&quot; id=&quot;markdown-toc-暴力解决二维动态规划&quot;&gt;暴力解决：二维动态规划&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#改进1一维动态规划优化空间复杂度&quot; id=&quot;markdown-toc-改进1一维动态规划优化空间复杂度&quot;&gt;改进1：一维动态规划——（优化空间复杂度）&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;01背包&quot;&gt;0/1背包&lt;/h2&gt;

&lt;h4 id=&quot;暴力解决二维动态规划&quot;&gt;暴力解决：二维动态规划&lt;/h4&gt;

&lt;ul&gt;
  &lt;li&gt;二维dp的定义：$f[i][j]​$: 考虑前i个物品，总体积为j的最大价值为$f[i][j]​$&lt;/li&gt;
  &lt;li&gt;返回结果：$max(f[n][0~v])$,因为背包可以不填满，因此也存在不被选择的物体&lt;/li&gt;
  &lt;li&gt;递推公式：
    &lt;ul&gt;
      &lt;li&gt;不选择第i个物品：$f[i][j]=f[i-1][j]$&lt;/li&gt;
      &lt;li&gt;选择第i个物品：$f[i][j]=max(f[i-1][j],f[i-1][j-v[i]]+w[i])​$&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;初始化：$f[0][0]=0​$&lt;/li&gt;
  &lt;li&gt;复杂度：
    &lt;ul&gt;
      &lt;li&gt;时间复杂度：$O(nv)​$&lt;/li&gt;
      &lt;li&gt;空间复杂度：$O(n^2)​$&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-c++ highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cp&quot;&gt;#include&amp;lt;iostream&amp;gt;
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;using&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;namespace&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;

&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;main&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;cin&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cin&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;dp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;dp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//不选第i个物品
&lt;/span&gt;            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//选第i个物品
&lt;/span&gt;            &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;dp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]);&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;//背包可能没填满，但是要遍历完所有的背包
&lt;/span&gt;    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;res&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;res&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;res&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;cout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;res&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;改进1一维动态规划优化空间复杂度&quot;&gt;改进1：一维动态规划——（优化空间复杂度）&lt;/h4&gt;

&lt;ul&gt;
  &lt;li&gt;
    定义dp数组：dp[j],表示容量为j时，最大的价值.
  &lt;/li&gt;
  &lt;li&gt;
    递推公式：

    &lt;ul&gt;
      &lt;li&gt;$dp[j]=max(dp[j-v[i]]+w[i])​$&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    技巧

    &lt;ul&gt;
      &lt;li&gt;
        子程序：1.要保证dp[j]的递推来自第i-1个物品。dp[j]对应第f[i][j]，那么要保证dp[j]的递推来自dp[i-1][j-V[i]]，就要让容量递减的计算，也就是计算dp[v]-&amp;gt;dp[0].抽象一个一维数组解决0/1背包的子程序（处理第i个物品）：

        &lt;div class=&quot;language-c++ highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;zeroOnePack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[],&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[],&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//i为第i个物品
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;        &lt;/div&gt;
      &lt;/li&gt;
      &lt;li&gt;
        初始化

        &lt;ul&gt;
          &lt;li&gt;要求恰好装满背包：在初始化时除了F [0]为0，其它dp [1..v ]均设为−∞，这样就可以保证最终得到的dp[v ]是一种恰好装满背包的6最优解。&lt;/li&gt;
          &lt;li&gt;不要求装满背包:dp[0…v]=0&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;

    &lt;div class=&quot;language-c++ highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cp&quot;&gt;#include&amp;lt;iostream&amp;gt;
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;using&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;namespace&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
  
&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;main&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;cin&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
  
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cin&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
      
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;--&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;dp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]);&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;//or
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;//zeroOnePack(int dp,V,W,n,v,i);
&lt;/span&gt;    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;cout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;endl&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
&lt;/ul&gt;

</description>
        <pubDate>Sun, 23 Dec 2018 17:40:41 +0000</pubDate>
        <link>https://narcissuscyn.github.io/2018/12/23/01-%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98/</link>
        <guid isPermaLink="true">https://narcissuscyn.github.io/2018/12/23/01-%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98/</guid>
        
        <category>背包问题</category>
        
        
        <category>algorithm</category>
        
      </item>
    
      <item>
        <title>自平衡二叉搜索树</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#avl树&quot; id=&quot;markdown-toc-avl树&quot;&gt;AVL树&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#rb-tree&quot; id=&quot;markdown-toc-rb-tree&quot;&gt;RB-tree&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#性质&quot; id=&quot;markdown-toc-性质&quot;&gt;性质&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#实现&quot; id=&quot;markdown-toc-实现&quot;&gt;实现&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

C++ STL中标准关联容器set, multiset, map, multimap内部采用的就是一种非常高效的平衡检索二叉树：红黑树

是一种平衡的二叉搜索树，因而其查找的平均时间复杂度为元素总个数的对数（即logN）

&lt;h1 id=&quot;avl树&quot;&gt;AVL树&lt;/h1&gt;

插入时出现失衡的情况有如下四种（其中X为最小失衡子树的根节点）：

&lt;ol&gt;
  &lt;li&gt;插入点位于X的左子节点的左子树——左左；&lt;/li&gt;
  &lt;li&gt;插入点位于X的左子节点的右子树——左右；&lt;/li&gt;
  &lt;li&gt;插入点位于X的右子节点的左子树——右左；&lt;/li&gt;
  &lt;li&gt;插入点位于X的右子节点的右子树——右右。&lt;/li&gt;
&lt;/ol&gt;

情况1和4对称，称为外侧插入，可以采用单旋转操作调整恢复平衡；2和3对称，称为内侧插入，可以采用双旋转操作调整恢复平衡：先经过一次旋转变成左左或右右，然后再经过一次旋转恢复平衡，例如：

&lt;img src=&quot;https://narcissuspicbed.oss-cn-hangzhou.aliyuncs.com/IMAG2014080301.jpg&quot; alt=&quot;&quot; /&gt;

3，4类似于1，2。

&lt;h1 id=&quot;rb-tree&quot;&gt;RB-tree&lt;/h1&gt;

RB-tree的平衡条件不同于AVL-tree，但同样运用了单旋转和双旋转的恢复平衡的机制，下面我们详细介绍RB-tree的实现。

&lt;h2 id=&quot;性质&quot;&gt;性质&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;每个节点不是黑色就是红色；&lt;/li&gt;
  &lt;li&gt;根节点为&lt;strong&gt;黑色；&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;每个叶子节点（NIL）为黑色；&lt;/li&gt;
  &lt;li&gt;如果节点为红，其左右子节点必为黑；&lt;/li&gt;
  &lt;li&gt;对每个节点，从该节点到其子孙中的叶子节点的所有路径上所包含的黑色点数目相同。&lt;/li&gt;
&lt;/ul&gt;

这些约束保证了这个树大致上是平衡的，这也决定了&lt;strong&gt;红黑树的插入、删除、查询等操作是比较快速&lt;/strong&gt;的。 根据规则5，新增节点必须为红色；根据规则4，新增节点之父节点必须为黑色。当新增节点根据二叉搜索树的规则到达其插入点时，却未能符合上述条件时，就必须调整颜色并旋转树形。下图是一个典型的RB-tree（来自wiki）：

&lt;img src=&quot;https://narcissuspicbed.oss-cn-hangzhou.aliyuncs.com/IMAG2014080302.png&quot; alt=&quot;17  11  22 &quot; /&gt;

&lt;h2 id=&quot;实现&quot;&gt;实现&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;RB-tree的结构定义：主要包含一个标志颜色的bool变量 _M_color，3个节点指针 _M_parent , _M_left , _M_right，2个成员函数 _S_minimum 和 _S_maximum （分别求取最小（最左）、最大（最右）节点）&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-c++ highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;typedef&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;bool&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_Rb_tree_Color_type&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_Rb_tree_Color_type&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_S_rb_tree_red&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;const&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_Rb_tree_Color_type&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_S_rb_tree_black&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;//======================================
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_Rb_tree_node_base&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 节点的定义
&lt;/span&gt;  &lt;span class=&quot;k&quot;&gt;typedef&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_Rb_tree_Color_type&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_Color_type&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;typedef&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_Rb_tree_node_base&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_Base_ptr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;_Color_type&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_M_color&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 节点颜色，实际为一个bool型变量
&lt;/span&gt;  &lt;span class=&quot;n&quot;&gt;_Base_ptr&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_M_parent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 指向父节点，方便遍历
&lt;/span&gt;  &lt;span class=&quot;n&quot;&gt;_Base_ptr&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_M_left&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;_Base_ptr&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_M_right&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;

  &lt;span class=&quot;k&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_Base_ptr&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_S_minimum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;_Base_ptr&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;__x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;__x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;_M_left&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;__x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;__x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;_M_left&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;__x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_Base_ptr&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_S_maximum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;_Base_ptr&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;__x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;__x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;_M_right&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;__x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;__x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;_M_right&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;__x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;};&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;//======================================
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;template&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;_Value&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_Rb_tree_node&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_Rb_tree_node_base&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 节点的定义
&lt;/span&gt;  &lt;span class=&quot;k&quot;&gt;typedef&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_Rb_tree_node&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;_Value&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_Link_type&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;_Value&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_M_value_field&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;
    迭代器：自增自减操作
  &lt;/li&gt;
  &lt;li&gt;
    插入操作
  &lt;/li&gt;
  &lt;li&gt;
    &lt;ul&gt;
      &lt;li&gt;
        基本插入操作
      &lt;/li&gt;
      &lt;li&gt;
        调整至平衡
      &lt;/li&gt;
      &lt;li&gt;
        破坏RB-tree性质4的可能起因是&lt;strong&gt;插入了一个红色节点&lt;/strong&gt;、将一个&lt;strong&gt;黑色节点变为红色或者是旋转&lt;/strong&gt;，而破坏性质5的可能原因是&lt;strong&gt;插入一个黑色的节点&lt;/strong&gt;、&lt;strong&gt;节点颜色的改变（红变黑或黑变红）或者是旋转&lt;/strong&gt;。
      &lt;/li&gt;
      &lt;li&gt;
        &lt;strong&gt;新插入的节点的颜色必为红色&lt;/strong&gt;，因为插入黑点会增加某条路径上黑结点的数目，从而导致整棵树黑高度的不平衡。但如果新结点的父结点为红色时（如下图所示），将会违反红黑树的性质：一条路径上不能出现父子同为红色结点。这时就需要通过一系列操作来使红黑树保持平衡。为了清楚地表示插入操作以下在结点中使用“N”字表示一个新插入的结点，使用“P”字表示新插入点的父结点，使用“U”字表示“P”结点的兄弟结点，使用“G”字表示“P”结点的父结点。插入操作分为以下几种情况：
      &lt;/li&gt;
      &lt;li&gt;
        &lt;ul&gt;
          &lt;li&gt;树为空&lt;/li&gt;
          &lt;li&gt;
            &lt;ul&gt;
              &lt;li&gt;将插入节点改成黑色以满足性质2&lt;/li&gt;
            &lt;/ul&gt;
          &lt;/li&gt;
          &lt;li&gt;黑父（插入时不影响平衡）&lt;/li&gt;
          &lt;li&gt;
            &lt;ul&gt;
              &lt;li&gt;红黑树比AVL树优秀的地方之一在于黑父的情况比较常见，从而使红黑树需要旋转的几率相对AVL树来说会少一些。&lt;/li&gt;
            &lt;/ul&gt;
          &lt;/li&gt;
          &lt;li&gt;
            红父（复杂）

            由于父节点为红，所以祖父节点必为黑色。由于新节点和父节点均为红，所以需要重新着色或进行旋转，此时就需要考虑叔父节点的颜色，进而可能需要考虑祖父、祖先节点的颜色。

            &lt;ul&gt;
              &lt;li&gt;
                &lt;strong&gt;叔父为红&lt;/strong&gt;

                &lt;img src=&quot;https://narcissuspicbed.oss-cn-hangzhou.aliyuncs.com/IMAG2014080303.png&quot; alt=&quot;img&quot; /&gt;
              &lt;/li&gt;
              &lt;li&gt;
                &lt;strong&gt;叔父为黑&lt;/strong&gt;

                &lt;img src=&quot;https://narcissuspicbed.oss-cn-hangzhou.aliyuncs.com/IMAG2014080304.png&quot; alt=&quot; &quot; /&gt;
              &lt;/li&gt;
            &lt;/ul&gt;
          &lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    删除操作(复杂)
  &lt;/li&gt;
  &lt;li&gt;查询操作（简单O(logN))&lt;/li&gt;
&lt;/ul&gt;

</description>
        <pubDate>Sun, 28 Oct 2018 17:40:41 +0000</pubDate>
        <link>https://narcissuscyn.github.io/2018/10/28/%E7%BA%A2%E9%BB%91%E6%A0%91%E7%9A%84%E7%90%86%E8%A7%A3/</link>
        <guid isPermaLink="true">https://narcissuscyn.github.io/2018/10/28/%E7%BA%A2%E9%BB%91%E6%A0%91%E7%9A%84%E7%90%86%E8%A7%A3/</guid>
        
        
        <category>数据结构</category>
        
      </item>
    
      <item>
        <title>relation network for object detection</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#整体思路&quot; id=&quot;markdown-toc-整体思路&quot;&gt;整体思路&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;整体思路&quot;&gt;整体思路&lt;/h1&gt;

&lt;img src=&quot;https://ws1.sinaimg.cn/large/005IsqTWgy1fvm0sxgcjkj30fb0aq41o.jpg&quot; alt=&quot;图1 网络结构&quot; /&gt;

&lt;center&gt;图1 整体结构&lt;/center&gt;

主要是在原来的四阶段检测的基础上增加了&lt;strong&gt;关系信息模块&lt;/strong&gt;，在&lt;strong&gt;instance recognition&lt;/strong&gt;模块，FC模块和relation模块的输入输出都是一样的，因此能直接加入到FC层之后，这个relation模块主要是利用了每个物体与其他物体之间的关系，它的建立是基于原始attention model改的。而&lt;strong&gt;duplicate removal&lt;/strong&gt;模块主要是代替NMS，进行一个二分类，去除一些重复的框。

</description>
        <pubDate>Tue, 25 Sep 2018 00:00:00 +0000</pubDate>
        <link>https://narcissuscyn.github.io/2018/09/25/relation-network-for-object-detection/</link>
        <guid isPermaLink="true">https://narcissuscyn.github.io/2018/09/25/relation-network-for-object-detection/</guid>
        
        <category>ObjectDetection</category>
        
        <category>RelationshipDetection</category>
        
        
        <category>图像理解</category>
        
      </item>
    
      <item>
        <title>Deep Visual-Semantic Alignments for Generating Image Description</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#deep-visual-semantic-alignments-for-generating-image-description&quot; id=&quot;markdown-toc-deep-visual-semantic-alignments-for-generating-image-description&quot;&gt;Deep Visual-Semantic Alignments for Generating Image Description&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1 id=&quot;deep-visual-semantic-alignments-for-generating-image-description&quot;&gt;Deep Visual-Semantic Alignments for Generating Image Description&lt;/h1&gt;

</description>
        <pubDate>Sun, 23 Sep 2018 13:50:39 +0000</pubDate>
        <link>https://narcissuscyn.github.io/2018/09/23/deep_visual_sematntic_alignment/</link>
        <guid isPermaLink="true">https://narcissuscyn.github.io/2018/09/23/deep_visual_sematntic_alignment/</guid>
        
        <category>图像字幕</category>
        
        
        <category>图像理解</category>
        
      </item>
    
  </channel>
</rss>
