Fat pig’s piano bed (good question for dp)

Fat pig's piano bed

Question portal:

Fat pig's piano bed

Main idea:

Give you a 01 sequence and require all 1s to be connected together. You can change 0 to 1, or you can change 1 to 0. Ask what is the minimum number of operations.

Ideas:

From the title, we can immediately think that the final sequence must be in the form of 0000111110000. It is clearly divided into three segments, the first segment is 0, the second segment is 1, and the third segment is 0.
Each position may be one of these three paragraphs. We use dp [i] [0 ], dp [i] [1 ], dp [i] [2] to indicate that position i is the minimum number of operations in different segments.
You can get the recurrence
dp [i ][ 0] = dp [i-1] [0] + a[ i]-0
(When the current position is the first paragraph, the previous position must be the first paragraph)

dp [i ][ 1] = min( dp [i-1 ][ 0 ]+ 1-a[ i] ,dp [i -1 ][ 1] + 1-a[ i])
(when this position is in the first In the second paragraph, the previous position may be the first paragraph or the second paragraph)

dp [i ][ 2] = min( dp[ i-1 ][ 1] + a[ i]-0, dp[ i-1 ][ 2 ]+ a[ i]-0)
(when this position is in the first In the case of three paragraphs, the previous position may be the second paragraph or the third paragraph)

AC Code

#include<bits/stdc++.h>
using namespace std;
const int N=1e6+10;
int a[N],dp[N][3];
int main()
{
    
    
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        scanf("%1d",&a[i]);
    for(int i=1;i<=n;i++)
    {
    
    
        dp[i][0]=dp[i-1][0]+a[i];
        dp[i][1]=min(dp[i-1][0]+1-a[i],dp[i-1][1]+1-a[i]);
        dp[i][2]=min(dp[i-1][2]+a[i],dp[i-1][1]+a[i]);
    }
    int res=min(dp[n][0],dp[n][1]);
    res=min(res,dp[n][2]);
    printf("%d\n",res);
    system("pause");
    return 0;
}

Guess you like

Origin blog.csdn.net/Stevenwuxu/article/details/110778480