Advertisement
pdpd123

Problem 6

Feb 17th, 2020
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. typedef long long ll;
  4. typedef pair<int,int> pii;
  5. int dp[5010][5010][2],c[5010];
  6. int main(){
  7.     int n;
  8.     scanf("%d",&n);
  9.     memset(dp,0x3f,sizeof dp);
  10.     for(int i=1;i<=n;i++){
  11.         scanf("%d",c+i);
  12.         dp[i][i][0]=dp[i][i][1]=0;
  13.     }
  14.     for(int len=2;len<=n;len++){
  15.         for(int l=1;l+len-1<=n;l++){
  16.             int r=l+len-1;
  17.             if(c[l]==c[r]){
  18.                 int curv;
  19.                 curv=min(dp[l+1][r][1],dp[l+1][r][0]+1);
  20.                 if(c[l+1]==c[l]) curv=min(curv,dp[l+1][r][0]);
  21.                 curv=min(curv,min(dp[l][r-1][0],dp[l][r-1][1]+1));
  22.                 if(c[r-1]==c[r]) curv=min(curv,dp[l][r-1][1]);
  23.                 dp[l][r][0]=dp[l][r][1]=curv;
  24.             }else{
  25.                 int curv;
  26.                 curv=min(dp[l+1][r][0]+1,dp[l+1][r][1]+1);
  27.                 if(c[l+1]==c[l]) curv=min(curv,dp[l+1][r][0]);
  28.                 curv=min(curv,min(dp[l][r-1][0]+2,dp[l][r-1][1]+2));
  29.                 if(c[r]==c[r-1]) curv=min(curv,dp[l][r-1][1]+1);
  30.                 dp[l][r][0]=curv;
  31.                 curv=min(dp[l+1][r][0]+2,dp[l+1][r][1]+2);
  32.                 if(c[l]==c[l+1]) curv=min(curv,dp[l+1][r][0]+1);
  33.                 curv=min(curv,min(dp[l][r-1][0]+1,dp[l][r-1][1]+1));
  34.                 if(c[r]==c[r-1]) curv=min(curv,dp[l][r-1][1]);
  35.                 dp[l][r][1]=curv;
  36.             }
  37.         }
  38.     }
  39.     printf("%d\n",min(dp[1][n][0],dp[1][n][1]));
  40.     return 0;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement