[Minimum number of characters inserted when DP generates a return string] poj 1159

Source: Internet
Author: User

Note that the space complexity is optimized. The first 49776 K of the scrolling array is not used, and the last 188 K is used. This is the difference !!!

Transfer equation:

If (STR [I] = STR [J])
DP [I] [J] = DP [I-1] [J-1];
Else
DP [I] [J] = 1 + min (DP [I + 1] [J], DP [I] [J-1]);

# Include <map> # include <set> # include <list> # include <queue> # include <deque> # include <stack> # include <string> # include <time. h> # include <cstdio> # include <math. h> # include <iomanip> # include <cstdlib> # include <limits. h> # include <string. h> # include <iostream> # include <fstream> # include <algorithm> using namespace STD; # define ll long # define min int_min # define Max int_max # define PI ACOs (-1.0) # define fre Freopen ("input.txt", "r", stdin) # define FF freopen ("output.txt", "W", stdout) # define n 5005 /*********************************** * ********* if (STR [I] = STR [J]) DP [I] [J] = DP [I-1] [J-1]; else DP [I] [J] = 1 + min (DP [I + 1] [J], DP [I] [J-1]); **************************************** * *****/INT min (int, int B) {return A> B? B: A;} Char STR [N]; short DP [2] [N]; // short integer optimized space complexity int main () {int N; while (scanf ("% d % s", & N, STR + 1 )! =-1) {int I, j; memset (DP, 0, sizeof (DP); int K = 0; for (I = N; I> = 1; I --) {for (j = I + 1; j <= N; j ++) {if (I = J) {continue ;} if (STR [I] = STR [J]) {DP [k] [J] = DP [1-k] [J-1];} else DP [k] [J] = 1 + min (DP [1-k] [J], DP [k] [J-1]);} For (j = 1; j <= N; j ++) DP [1-k] [J] = DP [k] [J]; // The space complexity of rolling Array Optimization K ^ = 1 ;} printf ("% d \ n", DP [1-k] [N]);} return 0 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.