I learned from a simple DP question...

Source: Internet
Author: User
Tags cmath

Today, I want to learn about dynamic planning, so I read the courseware of hangdian, the data tower problem, and LCs are all classic dynamic specifications, then I started my exercises after class...

Hdoj 1421 move to bedroom

Http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1421

 

The K logarithm (2 * K) is selected from the number of n (n <= 2000) to minimize the sum of squares of their differences.

For example, 2 logarithm is selected from 8, 1, 10, 9, and 9. To minimize the sum of the squares of the difference, 8, 9, 9, and 10 are selected. The minimum result is 2.

 

 

Because I knew it was a DP question, I first created a DP [] [] array, and then I always wanted to select K pairs from N numbers, what is the relationship between K pairs selected from n-1 numbers...

Brother-in-law, I thought about it for a long time and thought about it. I searched for a question and looked at it,SortThe two big words touched my eyes...

As long as the N numbers are sorted in order, if the new number is to be used, it can only be different from the last and second number (n-1) (this cannot be guaranteed before sorting, so you cannot select). Then, if you select the K logarithm from the N number, there are two State sources:

1. If n numbers are not used, DP [N] [k] = DP [n-1] [k];

2. If the nth number is used, then DP [N] [k] = DP [N-2] [k-1] + (A [n]-A [n-1]) ^ 2

The state transition equation is DP [I] [J] = min (DP [I-1] [J], DP [I-2] [J-1] + (A [I]-A [I-1]) * (a [I]-A [I-1]);

 

Programming is as follows:

 1 #include<cstdio> 2 #include<cstring> 3 #include<cmath> 4 #include<algorithm> 5 #define INF 0x3f3f3f3f 6 #define MAXN 2005 7 using namespace std; 8 int a[MAXN]; 9 int dp[MAXN][MAXN];10 int main()11 {12   int n, k;13   while(scanf("%d%d", &n, &k) != EOF)14   {15     for (int i = 1; i <= n; ++i)16     {17       scanf("%d", &a[i]);18     }19     memset(dp, 0x3f, sizeof(dp));20     for (int i = 0; i < n + 1; ++i)21     {22       dp[i][0] = 0;23     }24 25     sort(a + 1, a + n + 1);26     for (int i = 2; i <= n; ++i)27     {28       for (int j = 1; j <= k, j <= i / 2; ++j)29       {30         dp[i][j] = min(dp[i-1][j], dp[i-2][j-1] + (a[i] - a[i-1]) * (a[i] - a[i-1]));31       }32     }33     printf("%d\n", dp[n][k]);34   }35   return 0;36 }

Insert an episode: For the definition of the maximum int value, here is the # define INF 0x3f3f3f ....

We know that the maximum value of 32-Int Is 0x7fffffff. It is no problem to define this value in this program. Let's talk about the difference between the two values:

1. If the defined maximum value is only used for comparison, for example, when a min is initialized, set inf to 0x7fffffff;

2. Many times we define a maximum value, which is not simply a comparison, but also a loose operation, such:

This code is available in many Shortest Path Algorithms.

If (d [u] + W [u] [v] <D [v]) d [v] = d [u] + W [u] [v];
We know that if there is no edge between U and V, W [u] [v] = inf. If our Inf is 0x7fffffff, then d [u] + W [u] [v] overflows and becomes a negative number.

That is to say, a constant or infinity should be added to an infinity, and 0x7fffff + 1 will overflow. Obviously, this does not meet this basic requirement.

So we found 0x3f3f3f3f (which is the first big God to use this number). Its value is 1061109567, that is, 10 ^ 9, which is an order of magnitude higher than 0x7fffffff, it adds a constant still in the range of 32int... more importantly, an infinite value should also be satisfied. positive infinity + positive infinity or infinity, exactly where 0x3f3f3f + 0x3f3f3f3f = 2122219134, this number is very large, but it does not exceed the 32-bit int expression range, so 0x3f3f3f3f also meets our "infinite plus infinity or infinity" requirements.

The most subtle thing is that when the memset () function is used to assign an initial value to an array, the four parameters 0,-1, true, and false are generally used, others may fail to reach the desired result (for example, if the value of 1 is fully assigned, it may not be 1), because memset is operated by byte, it can be used to clear the array because every byte of 0 is 0. Now, if we set the infinity to 0x3f3f3f3f, then the miracle will happen. Each byte of 0x3f3f3f is 0x3f! Therefore, to set all memory segments to infinity, we only need memset (A, 0x3f, sizeof ()).

In summary, 0x3f3f3f3f is really a good choice when assigning the maximum value.

 

 

Okay, let's go back to this program. After the code is submitted according to the code above, although it can be AC, the running time is 800 + ms, and the space is 15000 + K, this is obviously not the result we want to see...

Then we started to optimize it. After reading the program, it is obvious that the time-consuming process is not the process of evaluating the value of DP [] [], because in multiple groups of input data, not all groups require n = 2000, K = 1000. Obviously, when memset () is used to assign an initial value to DP, since each group of data needs to be initialized, each time it is a maxn ^ 2 time, it can be initialized according to N, K, there is no technical content...

For space optimization, it is obvious that I have a brainless int DP [maxn] [maxn];

Through the research program, we found that in the process of solving DP [I] [J], we only need to save three sets of I values, because DP [I] [J] only uses DP [I-1] [] and DP [I-2] [], for DP [I-3] [] and the previous data is not referenced, that is, the data is invalid... we only need to open an int DP [3] [maxn/2]; (k cannot exceed half of n ...)

Such an array is calledScrolling Array", Which is equivalent to writing it to DP [I-3] [] Every time after solving DP [I] [] in the original array, with only three positions, through this scroll, the maxn length is evaluated. This technique is very common in solving DP problems. It does not help in time, but the space saved is not half past one (think 2005*2005 and 3*2005 )...

Using the "rolling array" technique, we also reduced the initialization time of DP [] []... just change the state transition equation in the original program to the following:

DP [I % 3] [J] = min (DP [(I-1) % 3] [J], DP [(I-2) % 3] [J-1] + (A [I]-A [I-1]) * (a [I]-A [I-1]);

The code after the change is as follows, and the red part is the change content:

 1 #include<cstdio> 2 #include<cstring> 3 #include<cmath> 4 #include<cstdlib> 5 #include<algorithm> 6 #define INF 0x3f3f3f3f 7 #define MAXN 2005 8 using namespace std; 9 int a[MAXN];10 int dp[3][MAXN/2];11 int main()12 {13   int n, k;14   while(scanf("%d%d", &n, &k) != EOF)15   {16       17     for (int i = 1; i <= n; ++i)18     {19       scanf("%d", &a[i]);20     }21     for (int i = 0; i <= 2; ++i)22     {23       for (int j = 1; j < k + 1; ++j)24       {25         dp[i][j] = INF;26       }27       dp[i][0] = 0;28     }29 30     sort(a + 1, a + n + 1);31     for (int i = 2; i <= n; ++i)32     {33       for (int j = 1; j <= k; ++j)34       {35         dp[i%3][j] = min(dp[(i-1)%3][j], dp[(i-2)%3][j-1] + (a[i] - a[i-1]) * (a[i] - a[i-1]));36       }37     }38     printf("%d\n", dp[n%3][k]);39   }40   return 0;41 }

After the change, submit again for 90 ms, with a space of 240 KB. the first page of the solution ranking is displayed, which is an ideal result (compared with the previous 800 ms, 15000 K). If you are interested, you can optimize the input and output details and try best solution!

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.