UVA-10271 chopsticks (linear DP)

Source: Internet
Author: User

Title: In n number, find K ternary group (A<=B<=C), the smallest (a-B) * (A-B) sum.

Title Analysis: To sort all the numbers from large to small, define DP (I,J) to indicate the minimum and maximum number of J triples found in the first I, then the state transition equation is DP (I,J) =min (DP (I-1,J), DP (I-2,J-1)), The second decision is to be made on the premise that the first i-1 number constitutes the J-1 group and must have the remaining number. The problem is similar to "moving a bedroom" and "chopsticks", and the same should be solved by filling in the form and paying attention to borders.

The code is as follows:

# include<iostream># include<cstdio># include<cstring># include<algorithm>using namespace std;# define LL long longconst int inf=1<<30;int m,n,a[5005];int dp[5005][1010];int Solve () {    m+=8;    for (int i=0;i<n;++i) {        dp[i][0]=0;        for (int j=1;j<=m;++j) dp[i][j]=inf;    }    for (int i=2;i<n;++i) {for        (int j=1;j<=m;++j)            if (i>=3*j-1) dp[i][j]=min (dp[i-1][j],dp[i-2][j-1]+ (A [I]-a[i-1]) * (a[i]-a[i-1]));    }    return dp[n-1][m];} int main () {    int T;    scanf ("%d", &t);    while (t--)    {        scanf ("%d%d", &m,&n);        for (int i=n-1;i>=0;--i)            scanf ("%d", a+i);        printf ("%d\n", Solve ());    }    return 0;}

  

UVA-10271 chopsticks (linear DP)

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.