<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>fenwick tree Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/fenwick-tree/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/fenwick-tree/</link>
	<description></description>
	<lastBuildDate>Tue, 10 Nov 2020 00:24:23 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>fenwick tree Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/fenwick-tree/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1649. Create Sorted Array through Instructions</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1649-create-sorted-array-through-instructions/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1649-create-sorted-array-through-instructions/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 08 Nov 2020 19:35:26 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[fenwick tree]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[prefix sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7634</guid>

					<description><![CDATA[<p>Given an integer array&#160;instructions, you are asked to create a sorted array from the elements in&#160;instructions. You start with an empty container&#160;nums. For each element&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1649-create-sorted-array-through-instructions/">花花酱 LeetCode 1649. Create Sorted Array through Instructions</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given an integer array&nbsp;<code>instructions</code>, you are asked to create a sorted array from the elements in&nbsp;<code>instructions</code>. You start with an empty container&nbsp;<code>nums</code>. For each element from&nbsp;<strong>left to right</strong>&nbsp;in&nbsp;<code>instructions</code>, insert it into&nbsp;<code>nums</code>. The&nbsp;<strong>cost</strong>&nbsp;of each insertion is the&nbsp;<strong>minimum</strong>&nbsp;of the following:</p>



<ul><li>The number of elements currently in&nbsp;<code>nums</code>&nbsp;that are&nbsp;<strong>strictly less than</strong>&nbsp;<code>instructions[i]</code>.</li><li>The number of elements currently in&nbsp;<code>nums</code>&nbsp;that are&nbsp;<strong>strictly greater than</strong>&nbsp;<code>instructions[i]</code>.</li></ul>



<p>For example, if inserting element&nbsp;<code>3</code>&nbsp;into&nbsp;<code>nums = [1,2,3,5]</code>, the&nbsp;<strong>cost</strong>&nbsp;of insertion is&nbsp;<code>min(2, 1)</code>&nbsp;(elements&nbsp;<code>1</code>&nbsp;and&nbsp;<code>2</code>&nbsp;are less than&nbsp;<code>3</code>, element&nbsp;<code>5</code>&nbsp;is greater than&nbsp;<code>3</code>) and&nbsp;<code>nums</code>&nbsp;will become&nbsp;<code>[1,2,3,3,5]</code>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>total cost</strong>&nbsp;to insert all elements from&nbsp;</em><code>instructions</code><em>&nbsp;into&nbsp;</em><code>nums</code>. Since the answer may be large, return it&nbsp;<strong>modulo</strong>&nbsp;<code>10<sup>9</sup>&nbsp;+ 7</code></p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> instructions = [1,5,6,2]
<strong>Output:</strong> 1
<strong>Explanation:</strong> Begin with nums = [].
Insert 1 with cost min(0, 0) = 0, now nums = [1].
Insert 5 with cost min(1, 0) = 0, now nums = [1,5].
Insert 6 with cost min(2, 0) = 0, now nums = [1,5,6].
Insert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6].
The total cost is 0 + 0 + 0 + 1 = 1.</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> instructions = [1,2,3,6,5,4]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Begin with nums = [].
Insert 1 with cost min(0, 0) = 0, now nums = [1].
Insert 2 with cost min(1, 0) = 0, now nums = [1,2].
Insert 3 with cost min(2, 0) = 0, now nums = [1,2,3].
Insert 6 with cost min(3, 0) = 0, now nums = [1,2,3,6].
Insert 5 with cost min(3, 1) = 1, now nums = [1,2,3,5,6].
Insert 4 with cost min(3, 2) = 2, now nums = [1,2,3,4,5,6].
The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3.
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> instructions = [1,3,3,3,2,4,2,1,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> Begin with nums = [].
Insert 1 with cost min(0, 0) = 0, now nums = [1].
Insert 3 with cost min(1, 0) = 0, now nums = [1,3].
Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3].
Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3,3].
Insert 2 with cost min(1, 3) = 1, now nums = [1,2,3,3,3].
Insert 4 with cost min(5, 0) = 0, now nums = [1,2,3,3,3,4].
​​​​​​​Insert 2 with cost min(1, 4) = 1, now nums = [1,2,2,3,3,3,4].
​​​​​​​Insert 1 with cost min(0, 6) = 0, now nums = [1,1,2,2,3,3,3,4].
​​​​​​​Insert 2 with cost min(2, 4) = 2, now nums = [1,1,2,2,2,3,3,3,4].
The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= instructions.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= instructions[i] &lt;= 10<sup>5</sup></code></li></ul>



<h2><strong>Solution: Fenwick Tree / Binary Indexed Tree</strong></h2>



<p>Time complexity: O(nlogm)<br>Space complexity: O(m + n)</p>



<p>m is the maximum value, n is number of values.</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">class FenwickTree {    
public:
  FenwickTree(int n): sums_(n + 1, 0) {}

  void update(int i, int delta) {
    while (i &lt; sums_.size()) {
        sums_[i] += delta;
        i += lowbit(i);
    }
  }

  int query(int i) const {        
    int sum = 0;
    while (i &gt; 0) {
        sum += sums_[i];
        i -= lowbit(i);
    }
    return sum;
  }
private:
  static inline int lowbit(int x) { 
    return x &amp; (-x); 
  }
  vector&lt;int&gt; sums_;
};

class Solution {
public:
  int createSortedArray(vector&lt;int&gt;&amp; instructions) {
    const int n = instructions.size();
    FenwickTree tree(1e5);
    long ans = 0;
    for (int i = 0; i &lt; n; ++i) {
      int lt = tree.query(instructions[i] - 1);
      int gt = i - tree.query(instructions[i]);      
      ans += min(lt, gt);
      tree.update(instructions[i], 1);
    }
    return ans % 1000000007;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1649-create-sorted-array-through-instructions/">花花酱 LeetCode 1649. Create Sorted Array through Instructions</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1649-create-sorted-array-through-instructions/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1409. Queries on a Permutation With Key</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-1409-queries-on-a-permutation-with-key/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-1409-queries-on-a-permutation-with-key/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 12 Apr 2020 06:02:52 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[fenwick tree]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[smulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6597</guid>

					<description><![CDATA[<p>Given the array&#160;queries&#160;of positive integers between&#160;1&#160;and&#160;m, you have to process all&#160;queries[i]&#160;(from&#160;i=0&#160;to&#160;i=queries.length-1) according to the following rules: In the beginning, you have the permutation&#160;P=[1,2,3,...,m]. For the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1409-queries-on-a-permutation-with-key/">花花酱 LeetCode 1409. Queries on a Permutation With Key</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1409. Queries on a Permutation With Key - 刷题找工作 EP319" width="500" height="375" src="https://www.youtube.com/embed/DwtijVbS3G0?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given the array&nbsp;<code>queries</code>&nbsp;of positive integers between&nbsp;<code>1</code>&nbsp;and&nbsp;<code>m</code>, you have to process all&nbsp;<code>queries[i]</code>&nbsp;(from&nbsp;<code>i=0</code>&nbsp;to&nbsp;<code>i=queries.length-1</code>) according to the following rules:</p>



<ul><li>In the beginning, you have the permutation&nbsp;<code>P=[1,2,3,...,m]</code>.</li><li>For the current&nbsp;<code>i</code>, find the position of&nbsp;<code>queries[i]</code>&nbsp;in the permutation&nbsp;<code>P</code>&nbsp;(<strong>indexing from 0</strong>) and then move this at the beginning of the permutation&nbsp;<code>P.</code>&nbsp;Notice that the position of&nbsp;<code>queries[i]</code>&nbsp;in&nbsp;<code>P</code>&nbsp;is the result for&nbsp;<code>queries[i]</code>.</li></ul>



<p>Return an array containing the result for the given&nbsp;<code>queries</code>.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> queries = [3,1,2,1], m = 5
<strong>Output:</strong> [2,1,2,1] 
<strong>Explanation:</strong> The queries are processed as follow: 
For i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is <strong>2</strong>, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5]. 
For i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is <strong>1</strong>, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5]. 
For i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is <strong>2</strong>, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5]. 
For i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is <strong>1</strong>, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5]. 
Therefore, the array containing the result is [2,1,2,1].  
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> queries = [4,1,2,2], m = 4
<strong>Output:</strong> [3,1,2,0]
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> queries = [7,5,5,8,3], m = 8
<strong>Output:</strong> [6,5,0,7,5]
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= m &lt;= 10^3</code></li><li><code>1 &lt;= queries.length &lt;= m</code></li><li><code>1 &lt;= queries[i] &lt;= m</code></li></ul>



<h2><strong>Solution1: Simulation + Hashtable</strong></h2>



<p>Use a hashtable to store the location of each key.<br>For each query q, use h[q] to get the index of q, for each key, if its current index is less than q, increase their indices by 1. (move right). Set h[q] to 0.</p>



<p>Time complexity: O(q*m)<br>Space complexity: O(m)</p>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/04/1409-ep319-1.png" alt="" class="wp-image-6611" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/04/1409-ep319-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/04/1409-ep319-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/04/1409-ep319-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">class Solution {
public:
  vector&lt;int&gt; processQueries(vector&lt;int&gt;&amp; queries, int m) {
    vector&lt;int&gt; p(m + 1);
    iota(begin(p), end(p), -1);
    vector&lt;int&gt; ans;
    for (int q : queries) {      
      ans.push_back(p[q]);
      for (int i = 1; i &lt;= m; ++i)
        if (p[i] &lt; p[q]) ++p[i];
      p[q] = 0;
    }      
    return ans;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Fenwick Tree + HashTable</strong></h2>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/04/1409-ep319-2.png" alt="" class="wp-image-6612" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/04/1409-ep319-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/04/1409-ep319-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/04/1409-ep319-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>Time complexity: O(qlogm)<br>Space complexity: O(m)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Fenwick {
public:
  explicit Fenwick(int n): vals_(n) {}
  
  // sum(A[1~i])
  int query(int i) const {
    int s = 0;
    while (i &gt; 0) {
      s += vals_[i];
      i -= i &amp; -i;
    }
    return s;
  }
  
  // A[i] += delta
  void update(int i, int delta) {
    while (i &lt; vals_.size()) {
      vals_[i] += delta;
      i += i &amp; -i;
    }
  }
private:
  vector&lt;int&gt; vals_;
};

class Solution {
public:
  vector&lt;int&gt; processQueries(vector&lt;int&gt;&amp; queries, int m) {
    Fenwick tree(m * 2  + 1);
    vector&lt;int&gt; pos(m + 1);
    for (int i = 1; i &lt;= m; ++i)     
      tree.update(pos[i] = i + m, 1);
    
    vector&lt;int&gt; ans;
    for (int q : queries) {
      ans.push_back(tree.query(pos[q] - 1));
      tree.update(pos[q], -1); // set to 0.      
      tree.update(pos[q] = m--, 1); // move to the front.
    }
    return ans;
  }
};</pre>
</div></div>



<div class="responsive-tabs">
<h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">class Fenwick:
  def __init__(self, n):
    self.n = n
    self.val = [0] * n
  
  def query(self, i):
    s = 0
    while i &gt; 0:
      s += self.val[i]
      i -= i &amp; -i
    return s
  
  def update(self, i, delta):
    while i &lt; self.n:
      self.val[i] += delta
      i += i &amp; -i
    
class Solution:
  def processQueries(self, queries: List[int], m: int) -&gt; List[int]:    
    pos = [i + m for i in range(m + 1)]
    tree = Fenwick(2 * m + 1)
    for i in range(1, m + 1): tree.update(i + m, 1)    
    ans = []
    for q in queries:
      ans.append(tree.query(pos[q] - 1))
      tree.update(pos[q], -1)
      pos[q] = m
      m -= 1
      tree.update(pos[q], 1)
    return ans</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1409-queries-on-a-permutation-with-key/">花花酱 LeetCode 1409. Queries on a Permutation With Key</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-1409-queries-on-a-permutation-with-key/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 Fenwick Tree / Binary Indexed Tree / 树状数组 SP3</title>
		<link>https://zxi.mytechroad.com/blog/sp/fenwick-tree-binary-indexed-tree-sp3/</link>
					<comments>https://zxi.mytechroad.com/blog/sp/fenwick-tree-binary-indexed-tree-sp3/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 04 Jan 2018 07:09:20 +0000</pubDate>
				<category><![CDATA[SP]]></category>
		<category><![CDATA[binary indexed tree]]></category>
		<category><![CDATA[fenwick tree]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1491</guid>

					<description><![CDATA[<p>本期节目中我们介绍了Fenwick Tree/Binary Indexed Tree/树状数组的原理和实现以及它在leetcode中的应用。 In this episode, we will introduce Fenwick Tree/Binary Indexed Tree, its idea and implementation and show its applications in leetcode. Fenwick&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/sp/fenwick-tree-binary-indexed-tree-sp3/">花花酱 Fenwick Tree / Binary Indexed Tree / 树状数组 SP3</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe title="花花酱 Fenwick Tree / Binary Indexed Tree - 刷题找工作 SP3" width="500" height="375" src="https://www.youtube.com/embed/WbafSgetDDk?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></p>
<p>本期节目中我们介绍了Fenwick Tree/Binary Indexed Tree/树状数组的原理和实现以及它在leetcode中的应用。<br>
In this episode, we will introduce Fenwick Tree/Binary Indexed Tree, its idea and implementation and show its applications in leetcode.</p>
<p>Fenwick Tree is mainly designed for solving the single point update range sum problems. e.g. what&#8217;s the sum between i-th and j-th element while the values of the elements are mutable.</p>
<p>Init the tree (include building all prefix sums) takes O(nlogn)</p>
<p>Update the value of an element takes O(logn)</p>
<p>Query the range sum takes O(logn)</p>
<p>Space complexity: O(n)</p>
<p><img class="alignnone size-full wp-image-1496" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/sp3-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/sp3-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/sp3-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/sp3-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script></p>
<p><ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins><br>
<script><br />
     (adsbygoogle = window.adsbygoogle || []).push({});<br />
</script></p>
<p><img class="alignnone size-full wp-image-1495" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/sp3-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/sp3-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/sp3-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/sp3-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><strong>Applications:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/data-structure/307-range-sum-query-mutable/">花花酱 307. Range Sum Query &#8211; Mutable</a></li>
<li><a href="http://zxi.mytechroad.com/blog/difficulty/hard/315-count-of-smaller-numbers-after-self/">花花酱 315. Count of Smaller Numbers After Self</a></li>
</ul>
<p><strong>Implementation:</strong></p>
<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">class FenwickTree {    
public:
    FenwickTree(int n): sums_(n + 1, 0) {}
    
    void update(int i, int delta) {
        while (i &lt; sums_.size()) {
            sums_[i] += delta;
            i += lowbit(i);
        }
    }
    
    int query(int i) const {        
        int sum = 0;
        while (i &gt; 0) {
            sum += sums_[i];
            i -= lowbit(i);
        }
        return sum;
    }
private:
    static inline int lowbit(int x) { 
        return x &amp; (-x); 
    }
    vector&lt;int&gt; sums_;
};</pre>

</div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">class FenwickTree {
    int sums_[];
    public FenwickTree(int n) {
        sums_ = new int[n + 1];
    }
    
    public void update(int i, int delta) {
        while (i &lt; sums_.length) {
            sums_[i] += delta;
            i += i &amp; -i;
        }
    }
    
    public int query(int i) {
        int sum = 0;
        while (i &gt; 0) {
            sum += sums_[i];
            i -= i &amp; -i;
        }
        return sum;
    }
}</pre>

</div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">class FenwickTree:
    def __init__(self, n):
        self._sums = [0 for _ in range(n + 1)]
        
    def update(self, i, delta):
        while i &lt; len(self._sums):
            self._sums[i] += delta
            i += i &amp; -i
    
    def query(self, i):
        s = 0
        while i &gt; 0:
            s += self._sums[i]
            i -= i &amp; -i
        return s</pre>
</div></div>


<h2><strong>Applications</strong></h2>



<ul><li><a href="https://zxi.mytechroad.com/blog/data-structure/307-range-sum-query-mutable/">https://zxi.mytechroad.com/blog/data-structure/307-range-sum-query-mutable/</a></li><li><a href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-315-count-of-smaller-numbers-after-self/">https://zxi.mytechroad.com/blog/algorithms/array/leetcode-315-count-of-smaller-numbers-after-self/</a></li><li><a href="https://zxi.mytechroad.com/blog/simulation/leetcode-1409-queries-on-a-permutation-with-key/">https://zxi.mytechroad.com/blog/simulation/leetcode-1409-queries-on-a-permutation-with-key/</a></li></ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/sp/fenwick-tree-binary-indexed-tree-sp3/">花花酱 Fenwick Tree / Binary Indexed Tree / 树状数组 SP3</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/sp/fenwick-tree-binary-indexed-tree-sp3/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 315. Count of Smaller Numbers After Self</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-315-count-of-smaller-numbers-after-self/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-315-count-of-smaller-numbers-after-self/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 04 Jan 2018 05:59:12 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[binary indexed tree]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[fenwick tree]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[reversed pairs]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1487</guid>

					<description><![CDATA[<p>题目大意：给你一个数组，对于数组中的每个元素，返回一共有多少在它之后的元素比它小。 Problem: You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-315-count-of-smaller-numbers-after-self/">花花酱 LeetCode 315. Count of Smaller Numbers After Self</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/2SVLYsq5W8M?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>题目大意：给你一个数组，对于数组中的每个元素，返回一共有多少在它之后的元素比它小。</p>
<p><strong>Problem:</strong></p>
<p>You are given an integer array <i>nums</i> and you have to return a new <i>counts</i> array. The <i>counts</i> array has the property where <code>counts[i]</code> is the number of smaller elements to the right of <code>nums[i]</code>.</p>
<p><b>Example:</b></p><pre class="crayon-plain-tag">Given nums = [5, 2, 6, 1]

To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.</pre><p>Return the array <code>[2, 1, 1, 0]</code>.</p>
<p><strong>Idea:</strong></p>
<p>Fenwick Tree / Binary Indexed Tree</p>
<p>BST</p>
<p><img class="alignnone size-full wp-image-1515" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><img class="alignnone size-full wp-image-1514" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><img class="alignnone size-full wp-image-1513" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-3.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/01/315-ep149-3-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<h1><strong>Solution 1: Binary Indexed Tree (Fenwick Tree)</strong></h1>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Runnning time: 32 ms
// Time complexity: O(nlogn)
// Space complexity: O(k), k is the number unique elements
class FenwickTree {    
public:
    FenwickTree(int n): sums_(n + 1, 0) {}
    
    void update(int i, int delta) {
        while (i &lt; sums_.size()) {
            sums_[i] += delta;
            i += lowbit(i);
        }
    }
    
    int query(int i) const {        
        int sum = 0;
        while (i &gt; 0) {
            sum += sums_[i];
            i -= lowbit(i);
        }
        return sum;
    }
private:
    static inline int lowbit(int x) { return x &amp; (-x); }
    vector&lt;int&gt; sums_;
};

class Solution {
public:
    vector&lt;int&gt; countSmaller(vector&lt;int&gt;&amp; nums) {
        // Sort the unique numbers
        set&lt;int&gt; sorted(nums.begin(), nums.end());
        // Map the number to its rank
        unordered_map&lt;int, int&gt; ranks;
        int rank = 0;
        for (const int num : sorted)
            ranks[num] = ++rank;
        
        vector&lt;int&gt; ans;
        FenwickTree tree(ranks.size());
        // Scan the numbers in reversed order
        for (int i = nums.size() - 1; i &gt;= 0; --i) {
            // Chechk how many numbers are smaller than the current number.
            ans.push_back(tree.query(ranks[nums[i]] - 1));
            // Increse the count of the rank of current number.
            tree.update(ranks[nums[i]], 1);
        }
        
        std::reverse(ans.begin(), ans.end());
        return ans;
    }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 28 ms
class Solution {
  private static int lowbit(int x) { return x &amp; (-x); }
  
  class FenwickTree {    
    private int[] sums;    
    
    public FenwickTree(int n) {
      sums = new int[n + 1];
    }

    public void update(int i, int delta) {    
      while (i &lt; sums.length) {
          sums[i] += delta;
          i += lowbit(i);
      }
    }

    public int query(int i) {       
      int sum = 0;
      while (i &gt; 0) {
          sum += sums[i];
          i -= lowbit(i);
      }
      return sum;
    }    
  };
  
  public List&lt;Integer&gt; countSmaller(int[] nums) {
    int[] sorted = Arrays.copyOf(nums, nums.length);
    Arrays.sort(sorted);
    Map&lt;Integer, Integer&gt; ranks = new HashMap&lt;&gt;();
    int rank = 0;
    for (int i = 0; i &lt; sorted.length; ++i)
      if (i == 0 || sorted[i] != sorted[i - 1])
        ranks.put(sorted[i], ++rank);
    
    FenwickTree tree = new FenwickTree(ranks.size());
    List&lt;Integer&gt; ans = new ArrayList&lt;Integer&gt;();
    for (int i = nums.length - 1; i &gt;= 0; --i) {
      int sum = tree.query(ranks.get(nums[i]) - 1);      
      ans.add(tree.query(ranks.get(nums[i]) - 1));
      tree.update(ranks.get(nums[i]), 1);
    }
    
    Collections.reverse(ans);
    return ans;
  }
}</pre><p></div></div></p>
<h1><strong>Solution 2: BST</strong></h1>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 26 ms
struct BSTNode {
    int val;
    int count;
    int left_count;
    BSTNode* left;
    BSTNode* right;    
    BSTNode(int val): val(val), count(1), left_count(0), left{nullptr}, right{nullptr} {}
    ~BSTNode() { delete left; delete right; }
    int less_or_equal() const { return count + left_count; }
};
class Solution {
public:
    vector&lt;int&gt; countSmaller(vector&lt;int&gt;&amp; nums) {
        if (nums.empty()) return {};
        std::reverse(nums.begin(), nums.end());
        std::unique_ptr&lt;BSTNode&gt; root(new BSTNode(nums[0]));
        vector&lt;int&gt; ans{0};
        for (int i = 1; i &lt; nums.size(); ++i)
            ans.push_back(insert(root.get(), nums[i]));
        std::reverse(ans.begin(), ans.end());
        return ans;
    }
private:
    // Returns the number of elements smaller than val under root.
    int insert(BSTNode* root, int val) {
        if (root-&gt;val == val) {
            ++root-&gt;count;
            return root-&gt;left_count;
        } else if (val &lt; root-&gt;val) {
            ++root-&gt;left_count;
            if (root-&gt;left == nullptr) {
                root-&gt;left = new BSTNode(val);            
                return 0;
            } 
            return insert(root-&gt;left, val);
        } else  {
            if (root-&gt;right == nullptr) {
                root-&gt;right = new BSTNode(val);
                return root-&gt;less_or_equal();
            }
            return root-&gt;less_or_equal() + insert(root-&gt;right, val);
        }
    }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 10 ms
class Solution {
  class Node {
    int val;
    int count;
    int left_count;
    Node left;
    Node right;
    public Node(int val) { this.val = val; this.count = 1; }
    public int less_or_equal() { return count + left_count; }
  }
  
  public List&lt;Integer&gt; countSmaller(int[] nums) {
    List&lt;Integer&gt; ans = new ArrayList&lt;&gt;();
    if (nums.length == 0) return ans;
    int n = nums.length;
    Node root = new Node(nums[n - 1]);
    ans.add(0);
    for (int i = n - 2; i &gt;= 0; --i)
      ans.add(insert(root, nums[i]));
    Collections.reverse(ans);
    return ans;
  }
  
  private int insert(Node root, int val) {
    if (root.val == val) {
      ++root.count;
      return root.left_count;
    } else if (val &lt; root.val) {
      ++root.left_count;
      if (root.left == null) {
        root.left = new Node(val);            
        return 0;
      } 
      return insert(root.left, val);
    } else  {
      if (root.right == null) {
        root.right = new Node(val);
        return root.less_or_equal();
      }
      return root.less_or_equal() + insert(root.right, val);
    }
  }
}</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-315-count-of-smaller-numbers-after-self/">花花酱 LeetCode 315. Count of Smaller Numbers After Self</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-315-count-of-smaller-numbers-after-self/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 307. Range Sum Query &#8211; Mutable</title>
		<link>https://zxi.mytechroad.com/blog/data-structure/307-range-sum-query-mutable/</link>
					<comments>https://zxi.mytechroad.com/blog/data-structure/307-range-sum-query-mutable/#comments</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 04 Jan 2018 05:27:14 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[Bit]]></category>
		<category><![CDATA[Data Structure]]></category>
		<category><![CDATA[fenwick tree]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[prefix sum]]></category>
		<category><![CDATA[range sum]]></category>
		<category><![CDATA[segment tree]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1482</guid>

					<description><![CDATA[<p>题目大意：给你一个数组，让你求一个范围之内所有元素的和，数组元素可以更改。 Problem: Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. The update(i, val) function modifies nums by updating the element at index i to val. Example: [crayon-663eacbbe2543180996957/]&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/data-structure/307-range-sum-query-mutable/">花花酱 307. Range Sum Query &#8211; Mutable</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>题目大意：给你一个数组，让你求一个范围之内所有元素的和，数组元素可以更改。</p>
<p><strong>Problem:</strong></p>
<p>Given an integer array <i>nums</i>, find the sum of the elements between indices <i>i</i> and <i>j</i> (<i>i</i> ≤ <i>j</i>), inclusive.</p>
<p>The <i>update(i, val)</i> function modifies <i>nums</i> by updating the element at index <i>i</i> to <i>val</i>.</p>
<p><b>Example:</b></p>
<pre class="crayon-plain-tag">Given nums = [1, 3, 5]

sumRange(0, 2) -&gt; 9
update(1, 2)
sumRange(0, 2) -&gt; 8</pre>
<p><b>Note:</b></p>
<ol>
<li>The array is only modifiable by the <i>update</i> function.</li>
<li>You may assume the number of calls to <i>update</i> and <i>sumRange</i> function is distributed evenly.</li>
</ol>
<p><strong>Idea:</strong></p>
<p>Fenwick Tree</p>
<p><strong>Solution:</strong></p>
<p>C++</p>
<p>Time complexity:</p>
<p>init O(nlogn)</p>
<p>query: O(logn)</p>
<p>update: O(logn)<br /><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p>
<pre class="crayon-plain-tag">// Author: Huahua
// Running time: 83 ms
class FenwickTree {    
public:
    FenwickTree(int n): sums_(n + 1, 0) {}
    
    void update(int i, int delta) {
        while (i &lt; sums_.size()) {
            sums_[i] += delta;
            i += lowbit(i);
        }
    }
    
    int query(int i) const {        
        int sum = 0;
        while (i &gt; 0) {
            sum += sums_[i];
            i -= lowbit(i);
        }
        return sum;
    }
private:
    static inline int lowbit(int x) { return x &amp; (-x); }
    vector&lt;int&gt; sums_;
};

class NumArray {
public:
    NumArray(vector&lt;int&gt; nums): nums_(std::move(nums)), tree_(nums_.size()) {
        for (int i = 0; i &lt; nums_.size(); ++i)
            tree_.update(i + 1, nums_[i]);
    }
    
    void update(int i, int val) {
        tree_.update(i + 1, val - nums_[i]);
        nums_[i] = val;
    }
    
    int sumRange(int i, int j) {
        return tree_.query(j + 1) - tree_.query(i);
    }
private:
    vector&lt;int&gt; nums_;
    FenwickTree tree_;
};</pre>

</div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
// Running time: 130 ms
class NumArray {
    FenwickTree tree_;
    int[] nums_;
    public NumArray(int[] nums) {
        nums_ = nums;
        tree_ = new FenwickTree(nums.length);
        for (int i = 0; i &lt; nums.length; ++i)
            tree_.update(i + 1, nums[i]);
    }
    
    public void update(int i, int val) {
        tree_.update(i + 1, val - nums_[i]);
        nums_[i] = val;
    }
    
    public int sumRange(int i, int j) {
        return tree_.query(j + 1) - tree_.query(i);
    }
class FenwickTree {
    int sums_[];
    public FenwickTree(int n) {
        sums_ = new int[n + 1];
    }
    
    public void update(int i, int delta) {
        while (i &lt; sums_.length) {
            sums_[i] += delta;
            i += i &amp; -i;
        }
    }
    
    public int query(int i) {
        int sum = 0;
        while (i &gt; 0) {
            sum += sums_[i];
            i -= i &amp; -i;
        }
        return sum;
    }
}
}</pre>

</div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 192 ms (&lt; 90.00%)
"""
class FenwickTree:
    def __init__(self, n):
        self._sums = [0 for _ in range(n + 1)]
        
    def update(self, i, delta):
        while i &lt; len(self._sums):
            self._sums[i] += delta
            i += i &amp; -i
    
    def query(self, i):
        s = 0
        while i &gt; 0:
            s += self._sums[i]
            i -= i &amp; -i
        return s
    
class NumArray:

    def __init__(self, nums):
        self._nums = nums
        self._tree = FenwickTree(len(nums))
        for i in range(len(nums)):
            self._tree.update(i + 1, nums[i])

    def update(self, i, val):
        self._tree.update(i + 1, val - self._nums[i])
        self._nums[i] = val
        

    def sumRange(self, i, j):
        return self._tree.query(j + 1) - self._tree.query(i)</pre>
</div></div>


<h2>Solution 2: Segment Tree</h2>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua, running time: 24 ms
class SegmentTreeNode {
public:
  SegmentTreeNode(int start, int end, int sum,
                  SegmentTreeNode* left = nullptr,
                  SegmentTreeNode* right = nullptr): 
    start(start),
    end(end),
    sum(sum),
    left(left),
    right(right){}      
  SegmentTreeNode(const SegmentTreeNode&amp;) = delete;
  SegmentTreeNode&amp; operator=(const SegmentTreeNode&amp;) = delete;
  ~SegmentTreeNode() {
    delete left;
    delete right;
    left = right = nullptr;
  }
  
  int start;
  int end;
  int sum;
  SegmentTreeNode* left;
  SegmentTreeNode* right;
};

class NumArray {
public:
  NumArray(vector&lt;int&gt; nums) {
    nums_.swap(nums);
    if (!nums_.empty())
      root_.reset(buildTree(0, nums_.size() - 1));
  }

  void update(int i, int val) {
    updateTree(root_.get(), i, val);
  }

  int sumRange(int i, int j) {
    return sumRange(root_.get(), i, j);
  }
private:
  vector&lt;int&gt; nums_;
  std::unique_ptr&lt;SegmentTreeNode&gt; root_;
  
  SegmentTreeNode* buildTree(int start, int end) {  
    if (start == end) {      
      return new SegmentTreeNode(start, end, nums_[start]);
    }
    int mid = start + (end - start) / 2;
    auto left = buildTree(start, mid);
    auto right = buildTree(mid + 1, end);
    auto node = new SegmentTreeNode(start, end, left-&gt;sum + right-&gt;sum, left, right);    
    return node;
  }
  
  void updateTree(SegmentTreeNode* root, int i, int val) {
    if (root-&gt;start == i &amp;&amp; root-&gt;end == i) {
      root-&gt;sum = val;
      return;
    }
    int mid = root-&gt;start + (root-&gt;end - root-&gt;start) / 2;
    if (i &lt;= mid) {
      updateTree(root-&gt;left, i, val);
    } else {      
      updateTree(root-&gt;right, i, val);
    }
    root-&gt;sum = root-&gt;left-&gt;sum + root-&gt;right-&gt;sum;
  }
  
  int sumRange(SegmentTreeNode* root, int i, int j) {    
    if (i == root-&gt;start &amp;&amp; j == root-&gt;end) {
      return root-&gt;sum;
    }
    int mid = root-&gt;start + (root-&gt;end - root-&gt;start) / 2;
    if (j &lt;= mid) {
      return sumRange(root-&gt;left, i, j);
    } else if (i &gt; mid) {
      return sumRange(root-&gt;right, i, j);
    } else {
      return sumRange(root-&gt;left, i, mid) + sumRange(root-&gt;right, mid + 1, j);
    }
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/data-structure/307-range-sum-query-mutable/">花花酱 307. Range Sum Query &#8211; Mutable</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/data-structure/307-range-sum-query-mutable/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
