<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chenglei Si on Medium]]></title>
        <description><![CDATA[Stories by Chenglei Si on Medium]]></description>
        <link>https://medium.com/@sichenglei1125?source=rss-34197c383fd4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zwWJLiW5CzO99g8x_xm_gg.png</url>
            <title>Stories by Chenglei Si on Medium</title>
            <link>https://medium.com/@sichenglei1125?source=rss-34197c383fd4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:04:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sichenglei1125/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Min Sum (DP)]]></title>
            <link>https://medium.com/@sichenglei1125/min-sum-dp-cc789ebd2dfa?source=rss-34197c383fd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc789ebd2dfa</guid>
            <category><![CDATA[competitive-programming]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <dc:creator><![CDATA[Chenglei Si]]></dc:creator>
            <pubDate>Wed, 05 Dec 2018 04:20:07 GMT</pubDate>
            <atom:updated>2018-12-05T04:20:07.571Z</atom:updated>
            <content:encoded><![CDATA[<p>Given a sequence of n digits, you need to put m plus signs among them os that the sum of the expression is the minimum.</p><p>This is a classical dynamic programming problem. Suppose the minimum sum of i plus signs with j digits is V(i, j). We only need to consider the position of the last sign because V(i,j)=V(i-1, k)+num[k+1, j], in which the last plus sign is at position k (after the kth digit). This is the transition equation of the probelm. Note the j≥i+1 and i≤k&lt;j.</p><p>Obviously if i=0, the min sum must be the number itself. This is the initial state for this problem.</p><pre>#include &lt;cstdio&gt;<br>#include &lt;cstring&gt;<br>#include &lt;cmath&gt;<br>#include &lt;iostream&gt;<br>#include &lt;algorithm&gt;<br>using namespace std;</pre><pre>int dp[100][200];<br>char str[500];</pre><pre>int change(int x, int y){<br> int t=0;<br> for(int i=x; i&lt;=y; i++){<br>  t*=10;<br>  t+=(str[i]-&#39;0&#39;);<br> }<br> return t;<br>}</pre><pre>int main(){<br> int n, m;<br> while(scanf(&quot;%d%d&quot;, &amp;m, &amp;n)){<br>  scanf(&quot;%s&quot;, str+1);<br>  memset(dp, 0, sizeof(dp));<br>  for(int i=1; i&lt;m; i++){<br>   for(int j=1; j&lt;=n; j++){<br>    dp[i][j]=999999999;<br>   }<br>  }<br>  for(int i=1; i&lt;=n; i++){<br>   dp[0][i] = change(1, i);<br>  }<br>  for(int i=1; i&lt;=m; i++){<br>   for(int j=i+1; j&lt;=n; j++){<br>    for(int k=i; k&lt;j; k++){<br>     dp[i][j]=min(dp[i][j], dp[i-1][k]+change(k+1, j));<br>    }<br>   }<br>  }<br>  printf(&quot;%d\n&quot;, dp[m][n]);<br> }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc789ebd2dfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[POJ2796 Feel Good]]></title>
            <link>https://medium.com/@sichenglei1125/poj2796-feel-good-61f64da27885?source=rss-34197c383fd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/61f64da27885</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <dc:creator><![CDATA[Chenglei Si]]></dc:creator>
            <pubDate>Wed, 28 Nov 2018 03:12:44 GMT</pubDate>
            <atom:updated>2018-11-28T03:12:44.140Z</atom:updated>
            <content:encoded><![CDATA[<p>Problem description: You are a given a sequence of non-negative numbers and you need to find a subsequence which the product of the sum of the numbers and the minimum the number in the subsequence is the maximum.</p><p>This is very similar to POJ 2559 Histogram. You can use an increasing stack to solve it in O(n) time. The idea is to iterate through every number in the sequence and each time take the current number as the minimum number in the subsequence. You then need to find the longest subsequence (in order to maximize the sum and hence the product) in which this number is the minimum. We keep a left boundary to know where the subsequence starts and the right boundary is the first number after the current number that is smaller than it.</p><p>If the new number is bigger than the stack top, we just push it. If it’s equal, then consecutive equal numbers will have the same boundaries and hence the same results, so we can just skip it. If it’s larger than the stack top, we use its index-1 as the right boundary and compute the required product (need to keep a sum array beforehand) using the stack top as the minimum number in the subsequence. The default left boundary is the number’s index itself (in the case where it is larger than the numbers before it), it should be updated to the index of the new top after popping (i.e. the index of the first number before it that is smaller it + 1).</p><p>Remember to add a -1 at the end of the stack so that it will compute the values for numbers left in the stack after iterating through all the input numbers.</p><pre>#include &lt;cstdio&gt;<br>#include &lt;algorithm&gt;<br>using namespace std;</pre><pre>#define MAXN 100005<br>typedef long long ll;<br>ll numbers[MAXN], sums[MAXN]={0};<br>int stack[MAXN], left[MAXN];</pre><pre>//numbers store the actual numbers<br>//stack stores the index<br>int main(){<br> int N, top=-1, L=1, R=1;<br> ll tmp, ans=0;<br> scanf(&quot;%d&quot;, &amp;N);<br> for(int i=1; i&lt;=N; i++){<br>  scanf(&quot;%lld&quot;, numbers+i);<br>  sums[i] = sums[i-1] + numbers[i];<br> }<br> numbers[N+1] = -1;</pre><pre>//build an increasing stack<br> for(int i=1; i&lt;=N+1; i++){<br>  if(top&lt;0 || numbers[i]&gt;numbers[stack[top]]){<br>   stack[++top] = i;<br>   left[i] = i;<br>  }<br>  else{<br>   if(numbers[i]==numbers[stack[top]]){<br>    continue;<br>   }</pre><pre>while(top&gt;=0 &amp;&amp; numbers[i]&lt;numbers[stack[top]]){<br>    tmp = numbers[stack[top]]*(sums[i-1]-sums[left[stack[top]]-1]);<br>    if(tmp &gt; ans){<br>     ans=tmp;<br>     L = left[stack[top]];<br>     R = i-1;<br>    }<br>    top--;<br>   }<br>   left[i] = left[stack[++top]];<br>   stack[top] = i;<br>  }<br> }<br> printf(&quot;%lld\n&quot;, ans);<br> printf(&quot;%d %d\n&quot;, L, R);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61f64da27885" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[POJ1661 JumpGame]]></title>
            <link>https://medium.com/@sichenglei1125/poj1661-jumpgame-3ce9490dcf?source=rss-34197c383fd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ce9490dcf</guid>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <dc:creator><![CDATA[Chenglei Si]]></dc:creator>
            <pubDate>Thu, 22 Nov 2018 12:04:07 GMT</pubDate>
            <atom:updated>2018-11-22T12:04:07.987Z</atom:updated>
            <content:encoded><![CDATA[<p>Problem: you are given a set of boards with their different heights and left and right ends. Jimmy is at some initial position above all boards and he needs to jump onto the boards one by one to the ground. There is a maximum height difference (maxH) he can jump at each step, if the next board is too low, Jimmy will die. Find the minimum time needed for Jimmy to land the ground suppose he jumps at a constant speed at 1 unit per unit time.</p><p>This is a dynamic programming problem. At each board, Jimmy can either jump off from the left end or the right end. From either end, Jimmy needs to jump to the next board (if there is a board below within maximum allowed height difference) and chooses to walk to the left or right end and jump again, where Jimmy ends up in a similar jumping situation.</p><p>We use two arrays LeftMinTIme and RightMinTime to store the minimum time needed from each board to land from its either left or right end. We can treat Jimmy’s initial position as a board with the same left and right end.</p><p>In a bottom-up approach, we can fill in the two arrays from the lowest board to the highest. If there is no board below and the current height is bigger than maxH or the drop to the next board is bigger than maxH, then the minimum landing time for current board infinity. Otherwise, it is the smaller one between the time needed jumping to the next board plus time of going from the left end or the right end of the <strong>next</strong> <strong>board</strong>.</p><p>Codes:</p><pre>// 0MS bottom up <br>#include &lt;iostream&gt;<br>#include &lt;cstdio&gt;<br>#include &lt;vector&gt;<br>#include &lt;cstring&gt;<br>#include &lt;algorithm&gt;<br>using namespace std;</pre><pre>int n, x, y, maxH;<br>#define MAXN 1005<br>#define INF 99999999</pre><pre>int leftMinTime[MAXN];<br>int rightMinTime[MAXN];</pre><pre>struct bd{<br>    int left, right, h;<br>    bool operator &lt; (const bd &amp;B) const{<br>        return h &gt; B.h;<br>    }<br>};</pre><pre>vector&lt;bd&gt; all;</pre><pre>int main(){<br>    int t, cur_x, cur_y, j, i;<br>    bd temp;<br>    scanf(&quot;%d&quot;, &amp;t);<br>    while(t--){<br>        scanf(&quot;%d%d%d%d&quot;, &amp;n, &amp;x, &amp;y, &amp;maxH);<br>        // reset everything<br>        memset(leftMinTime, 0, sizeof(leftMinTime));<br>        memset(rightMinTime, 0, sizeof(rightMinTime));<br>        all.clear();<br>        <br>        all.push_back(bd{x, x, y});<br>        for(int k=0; k&lt;n; k++){<br>            scanf(&quot;%d%d%d&quot;, &amp;temp.left, &amp;temp.right, &amp;temp.h);<br>            all.push_back(temp);<br>        }<br>        <br>        sort(all.begin(), all.end());<br>        for(i=n; i&gt;=0; i--){<br>            cur_y = all[i].h;<br>            //find board below left<br>            cur_x = all[i].left;<br>            for(j=i+1; j&lt;=n; j++){<br>                if(all[j].left &lt;= cur_x &amp;&amp; all[j].right &gt;= cur_x)<br>                    break;<br>            }<br>            if(j&gt;n){<br>                //no board below<br>                if(cur_y &gt; maxH)<br>                    leftMinTime[i] = INF;<br>                else<br>                    leftMinTime[i] = cur_y;<br>            }<br>            else{<br>                if(cur_y - all[j].h &gt; maxH)<br>                    leftMinTime[i] = INF;<br>                else{<br>                    leftMinTime[i] = cur_y - all[j].h + min(<br>                                                            cur_x - all[j].left + leftMinTime[j],<br>                                                            all[j].right - cur_x + rightMinTime[j]);</pre><pre>}<br>            }<br>            <br>            <br>            <br>            //find board below right<br>            cur_x = all[i].right;<br>            for(j=i+1; j&lt;=n; j++){<br>                if(all[j].left &lt;= cur_x &amp;&amp; all[j].right &gt;= cur_x){<br>                    break;<br>                }<br>            }<br>            if(j&gt;n){<br>                if(cur_y &gt; maxH)<br>                    rightMinTime[i] = INF;<br>                else<br>                    rightMinTime[i] = cur_y;<br>            }<br>            else if(cur_y - all[j].h &gt; maxH){<br>                rightMinTime[i] = INF;<br>            }<br>            else{<br>                rightMinTime[i] = cur_y - all[j].h + min(<br>                                                         cur_x - all[j].left + leftMinTime[j],<br>                                                         all[j].right - cur_x + rightMinTime[j]);<br>            }<br>            <br>        }<br>        printf(&quot;%d\n&quot;, leftMinTime[0]);<br>    }<br>}</pre><p>The top-down recursive approach may be more intuitive. We write a function called min_time to get the min time needed from the board to land. We use a bool parameter to decide whether Jimmy starts from the left or the right end of this board. Then we find the next board. We directly return infinity if no next board is within range, or the current height if the next step in reach is the land (base case). Then we call the recursive function again to find the minimum time needed from the next board to land. Then we add the height from this board to the next board and distance walking to the corresponding end of the next board. We choose the smaller one of the two and update our dp arrays.</p><p>Codes:</p><pre>//recursive function, 0MS<br>int min_time(int cur_bd, bool fromLeft){<br>    int i, xx, yy=allB[cur_bd].h;<br>    <br>    if(fromLeft &amp;&amp; LeftMinTime[cur_bd]!=0)<br>        return LeftMinTime[cur_bd];<br>    if((!fromLeft) &amp;&amp; RightMinTime[cur_bd]!=0)<br>        return RightMinTime[cur_bd];<br>    <br>    if(fromLeft)<br>        xx = allB[cur_bd].left;<br>    else<br>        xx = allB[cur_bd].right;<br>    <br>    i = cur_bd + 1;<br>    while(i&lt;=n){<br>        if(allB[i].left&lt;=xx &amp;&amp; allB[i].right&gt;=xx)<br>            break;<br>        i++;<br>    }<br>    if(i&gt;n){<br>        if(yy &gt; maxH){<br>            return INF;<br>        }<br>        else{<br>            return allB[cur_bd].h;<br>        }<br>    }<br>    else if(yy - allB[i].h &gt; maxH){<br>        return INF;<br>    }<br>    else{<br>        int min_left_i = min_time(i, 1);<br>        int min_right_i = min_time(i, 0);<br>        int dh = yy - allB[i].h;<br>        if(fromLeft){<br>            LeftMinTime[cur_bd]=dh+min(allB[cur_bd].left-allB[i].left+min_left_i,<br>                               allB[i].right-allB[cur_bd].left+min_right_i);<br>            return LeftMinTime[cur_bd];<br>        }<br>        else{<br>            RightMinTime[cur_bd]=dh+min(allB[cur_bd].right-allB[i].left+min_left_i,<br>                                allB[i].right-allB[cur_bd].right+min_right_i);<br>            return RightMinTime[cur_bd];<br>        }<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ce9490dcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[POJ1458 LCS]]></title>
            <link>https://medium.com/@sichenglei1125/poj1458-lcs-cffd2d9aedfa?source=rss-34197c383fd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/cffd2d9aedfa</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <dc:creator><![CDATA[Chenglei Si]]></dc:creator>
            <pubDate>Mon, 22 Oct 2018 12:10:42 GMT</pubDate>
            <atom:updated>2018-10-22T12:10:42.880Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the classic longest common subsequence problem. Consider the <em>i</em>th character in string<em> x </em>and the <em>j</em>th character in string y. And we use a 2D dp matrix to record the length of the longest common subsequence with the current two substrings. The function is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*dTXszvpR1dXUZ3E6X8rurg.png" /></figure><p>Take note if you are using string instead of a character array, it’s easier to use cin for input instead of using scanf.</p><pre>#include &lt;vector&gt;<br>#include &lt;algorithm&gt;<br>#include &lt;cstring&gt;<br>#include &lt;iostream&gt;<br>using namespace std;</pre><pre>int main(){<br> //using scanf to read a string is very tricky<br> //so use cin instead<br> string a, b;<br> while(cin&gt;&gt;a&gt;&gt;b){<br>  size_t l_a = a.length(), l_b = b.length();<br>  // initialized to be all 0s<br>  vector&lt; vector&lt;int&gt; &gt; dp(l_a+1, vector&lt;int&gt; (l_b+1, 0));<br>  for(int i=1; i&lt;=l_a; i++){<br>   for(int j=1; j&lt;=l_b; j++){<br>    if(a[i-1]==b[j-1])<br>     dp[i][j] = dp[i-1][j-1]+1;<br>    else<br>     dp[i][j] = max(dp[i-1][j], dp[i][j-1]);<br>   }<br>  }<br>  cout&lt;&lt;dp[l_a][l_b]&lt;&lt;endl;<br> }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cffd2d9aedfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[POJ3494 Max Submatrix]]></title>
            <link>https://medium.com/@sichenglei1125/poj3494-max-submatrix-b90c90952a7e?source=rss-34197c383fd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b90c90952a7e</guid>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Chenglei Si]]></dc:creator>
            <pubDate>Mon, 22 Oct 2018 05:30:34 GMT</pubDate>
            <atom:updated>2018-10-22T05:30:34.900Z</atom:updated>
            <content:encoded><![CDATA[<p>The input is an m*n matrix whose elements are either 0 or 1. The task is to find the number of elements of the largest submatrix of all 1’s.</p><p>This problem is the 2D version of POJ 2559 histogram. We can treat every line of the matrix as a histogram problem. However, in this case, the base of the rectangles are not aligned. We can calculate the height of each block and save in another matrix. In this way, we basically convert the max submatrix problem to a 2D histogram. We can just use an increasing stack for every row and store the max area.</p><p>One thing to take note is that, since we are using stack very frequently here, the STL stack is slower than an array-implemented stack. If you use STL stack, you might get TLE.</p><p>AC code:</p><pre>#include &lt;cstdio&gt;<br>#include &lt;stack&gt;<br>#include &lt;cstring&gt;<br>#include &lt;algorithm&gt;<br>using namespace std;</pre><pre>// height, index<br>// using STL stack is too slow <br>// because I am using stack very frequently here<br>// and that&#39;s slower than a array/vector<br>typedef pair&lt;int, int&gt; block;<br>const int M = 2005, N = 2005;<br>int mat[M][N], blocks[M][N], m, n;</pre><pre>int get_max(){<br> int max_area = 0;<br> block t;<br> // convert to 2D histogram<br> for(int i=1; i&lt;=m; i++){<br>  for(int j=1; j&lt;=n; j++){<br>   scanf(&quot;%d&quot;, &amp;mat[i][j]);<br>   if(mat[i][j]==0)<br>    blocks[i][j]=0;<br>   else<br>    blocks[i][j]=blocks[i-1][j]+1;<br>  }<br> }<br> for(int i=1; i&lt;=m; i++){<br>  block S[N];<br>  int top = -1;<br>  for(int j=1; j&lt;=n; j++){<br>   t = block(blocks[i][j], j);<br>   while(top&gt;=0 &amp;&amp; S[top].first&gt;=blocks[i][j]){<br>    t = S[top];<br>    top--;<br>    max_area=max(max_area, (j-t.second)*t.first);<br>   }<br>   top++;<br>   S[top]=(block(blocks[i][j], t.second));<br>  }<br>  while(top&gt;=0){<br>   t = S[top];<br>   top--;<br>   max_area = max(max_area, (n+1-t.second)*t.first);<br>  }<br> }<br> return max_area;<br>}</pre><pre>int main(){<br> while(~scanf(&quot;%d %d&quot;, &amp;m, &amp;n)){<br>  memset(mat, 0, sizeof(mat));<br>  memset(blocks, 0, sizeof(blocks));<br>  printf(&quot;%d\n&quot;, get_max());<br> }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b90c90952a7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[POJ2559 Histogram]]></title>
            <link>https://medium.com/@sichenglei1125/poj2559-histogram-63426fe0a68b?source=rss-34197c383fd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/63426fe0a68b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <category><![CDATA[stack]]></category>
            <dc:creator><![CDATA[Chenglei Si]]></dc:creator>
            <pubDate>Mon, 08 Oct 2018 01:54:37 GMT</pubDate>
            <atom:updated>2018-10-08T01:54:37.459Z</atom:updated>
            <content:encoded><![CDATA[<p>The question gives a sequence of blocks with the same width 1 and different heights. You are to find the largest possible rectangles that can be formed. For example, the largest possible rectangle that can be formed in the below example is the shaded area:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*k2VbziWLdm46pgNas1qhVA.gif" /></figure><p>One naive but intuitive algorithm is to iterate through every block, checking its left and right until finding a shorter block on each side(i.e. find the boundaries). In this way, you can find the largest rectangle with height equal to the height of the current block. This brute force method takes O(n²) time.</p><p>A better way is to use an increasing stack. Every time when we push in a new block, if the top of the stack is taller than the new block, it means that the rectangle stating with the top block has met its right boundary (found the first shorter block on the right). We can get the area of the rectangle starting from the top block by multiplying its height and the distance between its left and right boundary. But how do we get the left boundary? When we push in the new block, if the top block is taller, it means that the rectangle starting from this new block can extend left to the top block (because the top block is taller), so we update the left boundary of this new block. If the top block is already shorter than the new block, then its left boundary is just itself. (If queal heigh, can be handled in either way.) After this, we can pop the top block. We repeat this until the stack becomes empty or the top block is shorter than the new block. Then we can just push in the new block.</p><p>We can use a struct for the block to store its left boundary and height.</p><p>After processing all blocks, if there are blocks left in the stack, it means that these blocks do not have right boundaries (if they have they will be already popped). Hence the rectangles starting from them can extend all the way to the rightmost block.</p><p>Codes:</p><pre>#include &lt;cstdio&gt;<br>#include &lt;algorithm&gt;<br>#include &lt;stack&gt;<br>using namespace std;</pre><pre>typedef long long ll;<br>const int MAX = 100005;</pre><pre>typedef pair&lt;int, ll&gt; rect;<br>//build an increasing stack<br>void max_rect(int N){2<br>    ll h, temp_area, max_area=0;<br>    rect t;<br>    stack&lt;rect&gt; stk;<br>    for(int i=0; i&lt;N; i++){<br>        scanf(&quot;%lld&quot;, &amp;h);<br>        t = rect(i, h);<br>        //met right limit of rect<br>        while(!stk.empty() &amp;&amp; stk.top().second &gt;= h){<br>            t = stk.top();<br>            stk.pop();<br>            <br>            temp_area = (i - t.first)*t.second;<br>            max_area = max(temp_area, max_area);<br>        }<br>        //t.first: left limit to extend<br>        stk.push(rect(t.first, h));<br>    }<br>    while(!stk.empty()){<br>        t = stk.top();<br>        stk.pop();<br>        temp_area = (N - t.first)*t.second;<br>        max_area = max(temp_area, max_area);<br>    }<br>    printf(&quot;%lld\n&quot;, max_area);<br>}</pre><pre>int main(){<br>    int N;<br>    while(scanf(&quot;%d&quot;, &amp;N) &amp;&amp; N){<br>        max_rect(N);<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63426fe0a68b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stack]]></title>
            <link>https://medium.com/@sichenglei1125/stack-c316115a112?source=rss-34197c383fd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c316115a112</guid>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Chenglei Si]]></dc:creator>
            <pubDate>Tue, 02 Oct 2018 02:36:13 GMT</pubDate>
            <atom:updated>2018-10-02T11:57:55.398Z</atom:updated>
            <content:encoded><![CDATA[<p>Stack is a data structure that supports last in first out (LIFO). The implementation is very straightforward and I have attached a simple exercise to illustrate the use of a stack. This calculator implementation can be modified to support more powerful calculation (like multi-digit numbers, brackets, etc).</p><pre>//simple calculator with stack<br>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br>#include &lt;cassert&gt;<br>using namespace std;<br>//implement a stack (for practice)<br>//pls use STL stack in competition<br>template&lt;typename Type&gt; class Stack {<br>private:<br>    Type *elements;<br>    int top_index,max_size;<br>public:<br>    Stack(int length_input) {<br>        elements=new Type[length_input];<br>        max_size=length_input;<br>        top_index=-1;<br>    }<br>    ~Stack() {<br>        delete[] elements;<br>    }<br>    bool push(Type element) {<br>        if(top_index+1&gt;=max_size){<br>            return false;<br>        }<br>        top_index++;<br>        elements[top_index]=element;<br>        return true;<br>    }<br>    bool pop() {<br>        if(top_index&lt;0){<br>            return false;<br>        }<br>        top_index--;<br>        return true;<br>    }<br>    Type top() {<br>        assert(top_index&gt;=0);<br>        return elements[top_index];<br>    }<br>    bool empty() {<br>        return top_index&lt;0;<br>    }<br>};<br>//compare precedence of operators<br>bool precede(char cur, char top) {<br>    if((cur==&#39;*&#39;||cur==&#39;/&#39;)&amp;&amp;(top==&#39;+&#39;||top==&#39;-&#39;)){<br>        return true;<br>    }<br>    return false;<br>}</pre><pre>//do one calculation<br>float operate(char opr, float a, float b) {<br>    if(opr==&#39;+&#39;){<br>        return a+b;<br>    }<br>    else if(opr==&#39;-&#39;){<br>        return b-a;<br>    }<br>    else if(opr==&#39;*&#39;){<br>        return a*b;<br>    }<br>    else{<br>        return b/a;<br>    }<br>}</pre><pre>//use the top of the two stacks to do a calculation<br>//push back the result<br>void calc(Stack&lt;float&gt; &amp;numbers, Stack&lt;char&gt; &amp;operators) {<br>    float a=numbers.top();<br>    numbers.pop();<br>    float b=numbers.top();<br>    numbers.pop();<br>    numbers.push(operate(operators.top(),a,b));<br>    operators.pop();<br>}</pre><pre>int main() {<br>    int n;<br>    cin&gt;&gt;n;<br>    Stack&lt;float&gt; numbers(n);<br>    Stack&lt;char&gt; operators(n);<br>    string buffer;<br>    cin&gt;&gt;buffer;<br>    int i=0;<br>    while(i&lt;n){<br>        //only supports single digit<br>        if(isdigit(buffer[i])){<br>            numbers.push(buffer[i]-&#39;0&#39;);<br>            i++;<br>        }<br>        else{<br>            //if the new operators has higher precedence<br>            //push into stack first<br>            if(operators.empty()||precede(buffer[i],operators.top())){<br>                operators.push(buffer[i]);<br>                i++;<br>            }<br>            else{<br>                calc(numbers,operators);<br>            }<br>        }<br>    }<br>    //clear all calculation<br>    while(!operators.empty()){<br>        calc(numbers,operators);<br>    }<br>    //the last element left in stack is the result<br>    cout&lt;&lt;numbers.top()&lt;&lt;endl;<br>    return 0;<br>}</pre><p>A very useful type of stack is the increasing/decreasing stack where elements in the stack are in increasing/decreasing order.</p><p>For example, you are given a sequence of numbers. For each number, you need to find the nearest previous number that is less than this current number. We can keep an increasing stack to do this task. Every time, we push the new number into the stack and ensure that the stack is increasing. If there are numbers larger than the current number, we just pop them from the stack.</p><pre>//strictly increasing stack<br>//find the nearest previous inputs less than the current input<br>int main(){<br>    int n, top=-1,t;<br>    cin&gt;&gt;n;<br>    int a[100];   //the stack<br>    for(int i=0;i&lt;n;i++){<br>        cin&gt;&gt;t;<br>        while(top&gt;=0 &amp;&amp; a[top]&gt;=t){<br>            top--;<br>        }<br>        if(top==-1){<br>            cout&lt;&lt;t&lt;&lt;&quot; : &quot;&lt;&lt;&quot;no&quot;&lt;&lt;endl;<br>        }<br>        else{<br>            cout&lt;&lt;t&lt;&lt;&quot; : &quot;&lt;&lt;a[top]&lt;&lt;endl;<br>        }<br>        top++;<br>        a[top]=t;<br>    }<br>}</pre><p>An example of the application of the decreasing stack is the water pouring problem. You are given <em>n</em> boards with different heights in a row and an infinitely tall board in the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*HRIVx9tqVIusE8cpSim3mg.png" /><figcaption>pour water on the right side of the 4th board</figcaption></figure><p>For each board, we pour water on its right side until the height of the water reaches the height of this board. We need to find the total number of boards that are submerged in water.</p><p>This problem is equivalent to finding the first board on the right of each board that is taller (or equal height) as this current board. We can use a decreasing stack to solve this type of problem. Every time when we push a new board into the stack (from left to right), we check if the top board is shorter than the current board. If so, we have found its next taller board and we can just add the number of boards between them and pop that board. We repeat this process until the top board is taller than the current board.</p><p>The codes are more explanatory than words.</p><pre>//simplified<br>//decreasing stack<br>typedef pair&lt;int, int&gt; node;<br>int main(){<br>    int n, ans=0;<br>    cin&gt;&gt;n;<br>    node stack[100];<br>    int top=-1, t;<br>    for(int i=1; i&lt;=n; i++){<br>        cin&gt;&gt;t;<br>        //met the first taller board on the right, process and pop<br>        while(top&gt;=0 &amp;&amp; stack[top].second&lt;=t){<br>            ans+=(i-stack[top].first-1);<br>            top--;<br>        }<br>        top++;<br>        stack[top]=node(i, t);<br>    }<br>    //boards left have no taller boards on the right<br>    //use the last infinite board to process<br>    while(top&gt;=0){<br>        ans+=(n+1-stack[top].first-1);<br>        top--;<br>    }<br>    cout&lt;&lt;ans&lt;&lt;endl;<br>}</pre><p>(This problem is almost identical to POJ 3250 the bad hair day.) The decreasing stack solves it in O(n) time.</p><p>From these two examples, we can see that the increasing/decreasing stack is good at finding the nearest larger or smaller element.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c316115a112" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Programming 1]]></title>
            <link>https://medium.com/@sichenglei1125/dynamic-programming-1-f48b3eaecdd?source=rss-34197c383fd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f48b3eaecdd</guid>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <dc:creator><![CDATA[Chenglei Si]]></dc:creator>
            <pubDate>Tue, 18 Sep 2018 03:59:45 GMT</pubDate>
            <atom:updated>2018-09-18T03:59:45.341Z</atom:updated>
            <content:encoded><![CDATA[<p>We will explain the basic ideas of dynamic programming (DP) through a classic example: max sum triangle (POJ1163).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*5J_Foz05Q63i_Q6_gBp5qw.png" /></figure><p>You are given a number triangle and tasked to find a path so that the sum of all numbers on the path is the maximum. The path is from top to bottom and each time you can either go to the left child or the right child.</p><p>If we know the max sum of the left child and the right child, then we can find the max sum of the current position by choosing the max of the two children and add the number of current position, because for the current position, there are only two possible next steps: its left child or right child. In other words, we can find the global optimal by getting local optimal at every step.</p><p>We can store the results in a table to avoid repeated calculation and save time (this is very important for recursive solution).</p><p>Recursive solution: (top-down)</p><pre>int MaxSum(int r, int c){<br> if(dp[r][c]!=-1)<br>    return dp[r][c];<br> if(r==N)<br>    dp[r][c] = triangle[r][c];<br> else<br>    dp[r][c] = max(MaxSum(r+1, c), MaxSum(r+1, c+1)) + triangle[r][c];<br> return dp[r][c];<br>}</pre><p>Alternatively, we can solve this from base conditions and build up the entire solution.</p><pre>for(int i=1; i&lt;=N; i++){<br>  for(int j=1; j&lt;=i; j++){<br>   cin&gt;&gt;triangle[i][j];<br>  }<br> }<br> for(int i=N-1; i&gt;=1; i--){<br>  for(int j=1; j&lt;=i; j++){<br>   triangle[N][j]=max(triangle[N][j], triangle[N][j+1]) + triangle[i][j];<br>  }<br> }<br> cout&lt;&lt;triangle[N][1]&lt;&lt;endl;</pre><p>Note that we did not create another table to store the max sums, instead, we directly update the max sums in the last row of the triangle matrix (rolling array). This allows us to save some space.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f48b3eaecdd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Backpropagation Through Time]]></title>
            <link>https://medium.com/@sichenglei1125/backpropagation-through-time-3ba862633c13?source=rss-34197c383fd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ba862633c13</guid>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Chenglei Si]]></dc:creator>
            <pubDate>Fri, 14 Sep 2018 07:50:36 GMT</pubDate>
            <atom:updated>2018-09-14T07:51:03.613Z</atom:updated>
            <content:encoded><![CDATA[<p>This post shows the step-by-step derivation of backpropagation through time and implementation codes.</p><p>Suppose we have a many-to-many RNN and we are using the square loss. The total loss is the sum of all square loss over all the timesteps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kulXSh3Nz1StuQPc58sH5Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WxizPMq2Pow2h7Dq3hS8QQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yqj0TN6ToZ8UJDi3CdzDpg.jpeg" /></figure><p>The gradients in green boxes are used to update the parameters.</p><p>If you are using cross entropy loss instead, which usually uses softmax for output prediction, you need to use the derivative of softmax (shown above) instead, and all the steps after that are similar to using square loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y0x68K4_JqFA8HCKkg2RJQ.jpeg" /></figure><p>In a many-to-one RNN, things are even simpler because the gradient for hidden unit vector only consists of the error propagated form futures steps (unlike many-to-many which also has an error from current timestep). Other than that, the other derivations are similar.</p><p>Now, we can implement BPTT with Numpy with a toy example.</p><p>First, let’s try te many-to-many model. We use a many-to-many RNN to simulate binary addition. At each step, two binary digits are used as input and the correct sum of these two digits is used as the label. We use sigmoid activation for both hidden layers and output layers, the output predicted value is between 0 to 1.</p><p>Implementation: (following my BPTT steps for many-to-many above)</p><pre>import copy, numpy as np<br>np.random.seed(0)</pre><pre># compute sigmoid nonlinearity<br>def sigmoid(x):<br>    output = 1/(1+np.exp(-x))<br>    return output</pre><pre># convert output of sigmoid function to its derivative<br>def sigmoid_output_to_derivative(output):<br>    return output*(1-output)</pre><pre># training dataset generation<br>int2binary = {}<br>binary_dim = 8</pre><pre>largest_number = pow(2,binary_dim)<br>binary = np.unpackbits(<br>    np.array([range(largest_number)],dtype=np.uint8).T,axis=1)<br>for i in range(largest_number):<br>    int2binary[i] = binary[i]</pre><pre># input variables<br>alpha = 0.1<br>#set dx<br>input_dim = 2<br>#set da<br>hidden_dim = 16 <br>#set dy<br>output_dim = 1</pre><pre># initialize neural network weights<br>Wa = 2*np.random.random((input_dim,hidden_dim)) - 1<br>ba = np.zeros((1, hidden_dim))<br>Wy = 2*np.random.random((hidden_dim,output_dim)) - 1<br>by = np.zeros((1, output_dim))<br>Wh = 2*np.random.random((hidden_dim,hidden_dim)) - 1</pre><pre>Wa_update = np.zeros_like(Wa)<br>ba_update = np.zeros_like(ba)<br>Wy_update = np.zeros_like(Wy)<br>by_update = np.zeros_like(by)<br>Wh_update = np.zeros_like(Wh)</pre><pre># training <br>for j in range(10000):<br>    <br>    # generate a simple addition problem (a + b = c)<br>    a_int = np.random.randint(largest_number/2) # int version<br>    a = int2binary[a_int] # binary encoding</pre><pre>b_int = np.random.randint(largest_number/2) # int version<br>    b = int2binary[b_int] # binary encoding</pre><pre># true answer<br>    c_int = a_int + b_int<br>    c = int2binary[c_int]<br>    <br>    # where we&#39;ll store our best guess (binary encoded)<br>    d = np.zeros_like(c)</pre><pre>overallError = 0<br>    <br>    #list for k_deltas<br>    k_deltas = list()<br>    #list for a values<br>    a_values = list()<br>    #a&lt;0&gt; initializaed as 0 vector<br>    a_values.append(np.zeros(hidden_dim))<br>    <br>    # moving along the positions in the binary encoding<br>    for position in range(binary_dim):<br>        <br>        # generate input and output<br>        #input binary is processed in reverse order<br>        X = np.array([[a[binary_dim - position - 1],b[binary_dim - position - 1]]])<br>        y = np.array([[c[binary_dim - position - 1]]]).T</pre><pre># hidden layer (input ~+ prev_hidden)<br>        a_t = sigmoid(np.dot(X,Wa) + ba + np.dot(a_values[-1],Wh))</pre><pre># output layer (new binary representation)<br>        pred_yt = sigmoid(np.dot(a_t,Wy) + by)</pre><pre># did we miss?... if so, by how much?<br>        #loss function: 0.5*(y_pred - y)**2<br>        pred_yt_error = pred_yt - y<br>        k_deltas.append((pred_yt_error)*sigmoid_output_to_derivative(pred_yt))<br>        overallError += (0.5*pred_yt_error[0]**2)<br>    <br>        # store decoded predicted digit <br>        d[binary_dim - position - 1] = np.round(pred_yt[0][0])<br>        <br>        # store hidden layer so we can use it in the next timestep<br>        a_values.append(copy.deepcopy(a_t))<br>    <br>    #h&lt;T+1&gt;_delta initialized as 0 vector<br>    future_ht_delta = np.zeros(hidden_dim)<br>    <br>    for position in range(binary_dim):<br>        #backpropagate from last timestep <br>        X = np.array([[a[position],b[position]]])<br>        at = a_values[-position-1]<br>        #get a&lt;t-1&gt; for later use<br>        prev_at = a_values[-position-2]<br>        <br>        # error at output layer<br>        kt_delta = k_deltas[-position-1]<br>        # error at hidden layer<br>        ht_delta = (kt_delta.dot(Wy.T) + future_ht_delta.dot(Wh.T)) * sigmoid_output_to_derivative(at)</pre><pre># let&#39;s update all our weights so we can try again<br>        Wy_update += np.atleast_2d(at).T.dot(kt_delta)<br>        by_update += kt_delta<br>        Wh_update += np.atleast_2d(prev_at).T.dot(ht_delta)<br>        Wa_update += X.T.dot(ht_delta)<br>        ba_update += ht_delta<br>        <br>        future_ht_delta = ht_delta<br>    <br>    #gradient descent<br>    Wy -= Wy_update * alpha<br>    by -= by_update * alpha<br>    Wh -= Wh_update * alpha <br>    Wa -= Wa_update * alpha<br>    ba -= ba_update * alpha</pre><pre>#reset to 0 for next example<br>    Wy_update *= 0<br>    by_update *= 0<br>    Wh_update *= 0<br>    Wa_update *= 0<br>    ba_update *= 0<br>    <br>    # print out progress<br>    if(j % 1000 == 0):<br>        print (&quot;Error:&quot; + str(overallError))<br>        print (&quot;Pred:&quot; + str(d))<br>        print (&quot;True:&quot; + str(c))<br>        out = 0<br>        for index,x in enumerate(reversed(d)):<br>            out += x*pow(2,index)<br>        print (str(a_int) + &quot; + &quot; + str(b_int) + &quot; = &quot; + str(out))<br>        print (&quot;------------&quot;)</pre><p>Sample output: (you can reproduce the result by setting the same random seed)</p><pre>Error:[0.81597212]<br>Pred:[0 0 0 0 0 0 0 1]<br>True:[0 1 0 0 0 1 0 1]<br>9 + 60 = 1<br>------------<br>Error:[0.8360905]<br>Pred:[1 1 1 1 1 1 1 1]<br>True:[0 0 1 1 1 1 1 1]<br>28 + 35 = 255<br>------------<br>Error:[0.96656603]<br>Pred:[0 1 0 0 1 0 0 0]<br>True:[1 0 1 0 0 0 0 0]<br>116 + 44 = 72<br>------------<br>Error:[0.83946455]<br>Pred:[1 1 0 1 1 1 1 1]<br>True:[0 1 0 0 1 1 0 1]<br>4 + 73 = 223<br>------------<br>Error:[0.85176301]<br>Pred:[0 1 0 0 1 0 0 0]<br>True:[0 1 0 1 0 0 1 0]<br>71 + 11 = 72<br>------------<br>Error:[0.50600772]<br>Pred:[1 0 1 0 0 0 1 0]<br>True:[1 1 0 0 0 0 1 0]<br>81 + 113 = 162<br>------------<br>Error:[0.00943078]<br>Pred:[0 1 0 1 0 0 0 1]<br>True:[0 1 0 1 0 0 0 1]<br>81 + 0 = 81<br>------------<br>Error:[0.03681629]<br>Pred:[1 0 0 0 0 0 0 1]<br>True:[1 0 0 0 0 0 0 1]<br>4 + 125 = 129<br>------------<br>Error:[0.00784794]<br>Pred:[0 0 1 1 1 0 0 0]<br>True:[0 0 1 1 1 0 0 0]<br>39 + 17 = 56<br>------------<br>Error:[0.00440828]<br>Pred:[0 0 0 0 1 1 1 0]<br>True:[0 0 0 0 1 1 1 0]<br>11 + 3 = 14<br>------------</pre><p>From the output, you can see that the model is learning how to do binary number addition.</p><p>Next, we modify this task a bit to apply the many-to-one model. This step, we still use the binary digits as input, but instead of predicting the resultant binary digit as every timestep, we directly predict the base-10 (decimal) result at the end. Since we are directly predicting the base-10 (decimal) result, we do not need to use sigmoid activation for output anymore. This only requires a minor change of the formula for kt_delta, which is reflected in my codes below. Note that this time, we only update <em>Wy</em> and <em>by</em> at the last timestep.</p><p>Implementation: (following my BPTT steps for many-to-one above)</p><pre>import copy, numpy as np<br>import matplotlib.pyplot as plt <br>np.random.seed(0)</pre><pre># compute sigmoid nonlinearity<br>def sigmoid(x):<br>    output = 1/(1+np.exp(-x))<br>    return output</pre><pre># convert output of sigmoid function to its derivative<br>def sigmoid_output_to_derivative(output):<br>    return output*(1-output)</pre><pre># training dataset generation<br>int2binary = {}<br>binary_dim = 8</pre><pre>largest_number = pow(2,binary_dim)<br>binary = np.unpackbits(<br>    np.array([range(largest_number)],dtype=np.uint8).T,axis=1)<br>for i in range(largest_number):<br>    int2binary[i] = binary[i]</pre><pre># input variables<br>alpha = 0.1<br>#set dx<br>input_dim = 2<br>#set da<br>hidden_dim = 16 <br>#set dy<br>output_dim = 1</pre><pre>errors = []</pre><pre># initialize neural network weights<br>Wa = 2*np.random.random((input_dim,hidden_dim)) - 1<br>ba = np.zeros((1, hidden_dim))<br>Wy = 2*np.random.random((hidden_dim,output_dim)) - 1<br>by = np.zeros((1, output_dim))<br>Wh = 2*np.random.random((hidden_dim,hidden_dim)) - 1</pre><pre>Wa_update = np.zeros_like(Wa)<br>ba_update = np.zeros_like(ba)<br>Wy_update = np.zeros_like(Wy)<br>by_update = np.zeros_like(by)<br>Wh_update = np.zeros_like(Wh)</pre><pre># training <br>for j in range(100000):<br>    <br>    # generate a simple addition problem (a + b = c)<br>    a_int = np.random.randint(largest_number/2) # int version<br>    a = int2binary[a_int] # binary encoding</pre><pre>b_int = np.random.randint(largest_number/2) # int version<br>    b = int2binary[b_int] # binary encoding</pre><pre># true answer<br>    c_int = a_int + b_int<br>    <br>    overallError = 0<br>    <br>    #list for a values<br>    a_values = list()<br>    #a&lt;0&gt; initializaed as 0 vector<br>    a_values.append(np.zeros(hidden_dim))<br>    <br>    # moving along the positions in the binary encoding<br>    for position in range(binary_dim):<br>        <br>        # generate input and output<br>        #input binary is processed in reverse order<br>        X = np.array([[a[binary_dim - position - 1],b[binary_dim - position - 1]]])<br>        y = c_int</pre><pre># hidden layer (input ~+ prev_hidden)<br>        a_t = sigmoid(np.dot(X,Wa) + ba + np.dot(a_values[-1],Wh))</pre><pre># output layer <br>        # only the last timestep has output,<br>        # and only last timestep can update Wy, by<br>        if position == binary_dim-1:<br>            pred_yt = np.dot(a_t,Wy) + by</pre><pre>#loss function: 0.5*(y_pred - y)**2<br>            #no more sigmoid<br>            pred_yt_error = pred_yt[0][0] - y<br>        <br>            kT_delta = np.array([[pred_yt_error]])<br>            overallError = (0.5*pred_yt_error**2)<br>    <br>            # store decoded predicted digit <br>            final_pred = np.round(pred_yt[0][0])<br>        <br>        # store hidden layer so we can use it in the next timestep<br>        a_values.append(copy.deepcopy(a_t))<br>    <br>    #h&lt;T+1&gt;_delta initialized as 0 vector<br>    future_ht_delta = np.zeros(hidden_dim)<br>    <br>    for position in range(binary_dim):<br>        #backpropagate from last timestep <br>        X = np.array([[a[position],b[position]]])<br>        at = a_values[-position-1]<br>        #get a&lt;t-1&gt; for later use<br>        prev_at = a_values[-position-2]<br>        <br>        # error at hidden layer<br>        ht_delta = (future_ht_delta.dot(Wh.T)) * sigmoid_output_to_derivative(at)</pre><pre># let&#39;s update all our weights so we can try again<br>        if position == 0:<br>            Wy_update = np.atleast_2d(at).T.dot(kT_delta)<br>            by_update = kT_delta<br>        Wh_update += np.atleast_2d(prev_at).T.dot(ht_delta)<br>        Wa_update += X.T.dot(ht_delta)<br>        ba_update += ht_delta<br>        <br>        future_ht_delta = ht_delta<br>    <br>    #gradient descent<br>    Wy -= Wy_update * alpha<br>    by -= by_update * alpha<br>    Wh -= Wh_update * alpha <br>    Wa -= Wa_update * alpha<br>    ba -= ba_update * alpha</pre><pre>#reset to 0 for next example<br>    Wy_update *= 0<br>    by_update *= 0<br>    Wh_update *= 0<br>    Wa_update *= 0<br>    ba_update *= 0<br>    <br>    # print out progress<br>    if(j % 1000 == 0):<br>        print (&quot;Error:&quot; + str(overallError))<br>        errors.append(overallError)<br>        # print (&quot;Pred:&quot; + str(final_pred))<br>        # print (&quot;True:&quot; + str(c_int))<br>        # print (str(a_int) + &quot; + &quot; + str(b_int) + &quot; = &quot; + str(final_pred))<br>        # print (&quot;------------&quot;)</pre><pre>plt.plot(errors)<br>plt.xlabel(&#39;iterations&#39;)<br>plt.ylabel(&#39;loss&#39;)<br>plt.show()</pre><p>I also plotted the loss curve, and you can see that the loss is indeed decreasing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*5c-A9la8jPhXPKnojSOEzQ.png" /></figure><p>Sample output:</p><pre>Pred:-1.0<br>True:69<br>9 + 60 = -1.0<br>------------<br>Pred:114.0<br>True:95<br>18 + 77 = 114.0<br>------------<br>Pred:128.0<br>True:155<br>39 + 116 = 128.0<br>------------<br>Pred:173.0<br>True:170<br>95 + 75 = 173.0<br>------------<br>Pred:116.0<br>True:80<br>67 + 13 = 116.0<br>------------<br>Pred:192.0<br>True:181<br>99 + 82 = 192.0<br>------------<br>Pred:149.0<br>True:147<br>46 + 101 = 149.0<br>------------<br>Pred:130.0<br>True:112<br>5 + 107 = 130.0<br>------------<br>Pred:198.0<br>True:182<br>114 + 68 = 198.0<br>------------<br>Pred:163.0<br>True:200<br>109 + 91 = 163.0</pre><p>From the output, you may notice that it is harder to train the RNN to learn to add binary numbers to directly get the decimal result. This is because that in this case, the model not only needs to learn to add two binary numbers but also needs to learn how to convert the binary sum into the decimal result, while in the previous many-to-many example the RNN only needs to learn to do binary digit addition, which is easier.</p><p>Source code (many-to-many): <a href="https://github.com/NoviScl/DeepLearning/blob/master/tensorflow_tutorials/RNNaddition.py">https://github.com/NoviScl/DeepLearning/blob/master/tensorflow_tutorials/RNNaddition.py</a></p><p>(many-to-one): <a href="https://github.com/NoviScl/DeepLearning/blob/master/tensorflow_tutorials/RNNaddMany2One.py">https://github.com/NoviScl/DeepLearning/blob/master/tensorflow_tutorials/RNNaddMany2One.py</a></p><p>Reference: <a href="https://iamtrask.github.io/2015/11/15/anyone-can-code-lstm/">https://iamtrask.github.io/2015/11/15/anyone-can-code-lstm/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ba862633c13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[POJ2663 Tri Tiling]]></title>
            <link>https://medium.com/@sichenglei1125/poj2663-tri-tiling-f722de40fa17?source=rss-34197c383fd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f722de40fa17</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <dc:creator><![CDATA[Chenglei Si]]></dc:creator>
            <pubDate>Thu, 13 Sep 2018 01:56:59 GMT</pubDate>
            <atom:updated>2018-09-13T01:56:59.361Z</atom:updated>
            <content:encoded><![CDATA[<p>You are to fill a <em>3*n</em> rectangle with <em>1*2 </em>rectangles. With input n, you need to output the number of ways to fill the big rectangle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*UJaETPyhkN2h7fmVZuHHkg.png" /></figure><p>First, if n is odd, then the size of the big rectangle is odd, it is impossible to fill it with small rectangles with size 2. Hence, <em>n</em> must be even. Second, for a <em>3*n</em> rectangle, let’s consider its rightmost 2 columns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*K8XKnKBfNZUV1k94HyU2Ow.png" /></figure><p>Suppose there are<em> f(n)</em> ways to fill the entire rectangle, then there are <em>f(n-2) </em>ways to fill the left rectangle without the rightmost 2 columns. There are 3 different ways to fill the <em>3*2</em> (orange) rectangle: 3 horizontal blocks or 1 horizontal and 2 vertical blocks (can flip to get another filling). So there are <em>3*f(n-2)</em> ways of filling with the rightmost 2 columns filled nicely with 3 blocks.</p><p>Next, we consider the rightmost 4 columns. In order to avoid repetition, we do not count cases where the rightmost 2 columns are filled nicely with 3 blocks, because that case is already counted in the previous case. Then there are only 2 other ways to fill the big rectangle: the image below and its flip. Hence there are <em>2*f(n-4)</em> ways with the rightmost 4 columns filled up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/124/1*h2QLPnvEy1OP469dbTG6cQ.png" /></figure><p>Similarly, we consider the rightmost 6 columns. To avoid repetition, we don’t count cases where the rightmost 2 or 4 columns are filled up nicely. Then we only have 2 more ways: the image below and its flip. Hence we have <em>2*f(n-6) </em>more ways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*q_-EZIfxqpSWgY7iSH5rmA.png" /></figure><p>We can notice that there are only 2 more possible ways to all n&gt;2. Hence we derive the formula:</p><p><strong><em>f(n)=3f(n-2) + 2f(n-4) + 2f(n-6) + … + 2f(n-(n-2)) + 2</em></strong></p><p>The last term is 2 because there are 2 more ways if we consider the entire <em>n</em> columns without repetition with previous cases.</p><p>If we let <em>f(0)=1</em>, then the formula becomes:</p><p><em>f(n)=3f(n-2) + 2f(n-4) + 2f(n-6) + … + 2f(2) + 2f(0)</em></p><p>Sub the below quation into the above equation:</p><p><em>f(n-2)=3f(n-4) + 2f(n-6) + … + 2f(2) + 2f(0)</em></p><p>We get:</p><p><strong><em>f(n) = 4f(n-2)-f(n-4), where f(0)=1, f(2)=3</em></strong></p><p>Hence we just use a loop to get the answer.</p><p>Accepted solution:</p><pre>#include &lt;iostream&gt;<br>#include &lt;cstring&gt;<br>using namespace std;</pre><pre>int main(){<br> int dp[31], n;<br> memset(dp, 0, sizeof(dp));<br> dp[0]=1;<br> dp[2]=3;<br> while(true){<br>  cin&gt;&gt;n;<br>  if(n==-1) break;<br>  if(n%2==1)<br>   cout&lt;&lt;0&lt;&lt;endl;<br>  else if(dp[n]!=0)<br>   cout&lt;&lt;dp[n]&lt;&lt;endl;<br>  else{<br>   for(int i=4; i&lt;=n; i++){<br>    dp[i] = 4*dp[i-2] - dp[i-4];<br>   }<br>   cout&lt;&lt;dp[n]&lt;&lt;endl;<br>  }<br> }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f722de40fa17" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>