You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.
A picture is a barcode if the following conditions are fulfilled:
- All pixels in each column are of the same color.
- The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y.
The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y).
Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#".
In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists.
6 5 1 2
##.#.
.###.
###..
#...#
.##.#
###..
11
2 5 1 1
#####
.....
5
In the first test sample the picture after changing some colors can looks as follows:
.##..
.##..
.##..
.##..
.##..
.##..
In the second test sample the picture after changing some colors can looks as follows:
.#.#.
.#.#.
意思是有一个由 # .构成的字符数组每一列有.有#我们需要把它变成相同的但是如果相同的相邻的话那么相邻的列数最少为X最多为Y
首先如何状态转移因为相邻的列数最少为X最多为Y那我们就定住某一列然后枚举区间长度把这些区间里的列全部变成#或者.这时候就可以用到前缀和两个数组分别记录#和.的前缀和用的时候变成区间和就行了。
dp数组的含义 一维,1,0,表示最终列的字符。第二维表示到达该列的时候修改区间所需要的最小花费。
那么状态转移方程是 由另一个状态加上对应长度的区间和和当前状态不断的比较维护即
dp[1][i+j-1]=min(dp[1][i-1+j],dp[0][i-1]+z[i-1+j]-z[i-1]);
dp[0][i+j-1]=min(dp[0][i+j-1],dp[1][i-1]+p[i-1+j]-p[i-1]);
这个-1太麻烦了不如直接在枚举区间左端点的时候就将它-1然后就可以把状态转移方程改成
dp[1][i+j]=min(dp[1][i+j],dp[0][i]+z[i+j]-z[i]);
dp[0][i+j]=min(dp[0][i+j],dp[1][i]+p[i+j]-p[i]);
#include <iostream>
#include<cmath>
#include<string.h>
#include<string>
#include<queue>
#include<algorithm>
#include<stack>
#include<cstdio>
#include<set>
using namespace std;
long long inf=1e9+7;
int p[1009],z[1009];
int n,maxx=-1,x,y,x1,y1;
int dp[2][10000];
char ch[1009][1009];
int main()
{
cin>>x1>>y1>>x>>y;
for(int i=1;i<=x1;i++)
for(int j=1;j<=y1;j++)
scanf(" %c",&ch[i][j]);
n=y-x;
for(int i=1;i<=y1;i++)
{
for(int j=1;j<=x1;j++)
{
if(ch[j][i]=='#')
p[i]++;
else
z[i]++;
}
p[i]+=p[i-1];
z[i]+=z[i-1];
}
memset(dp,0x3f3f3f3f,sizeof(dp));
dp[0][0]=0,dp[1][0]=0;
for(int i=0;i<y1;i++)//区间统一左移
{
for(int j=x;j<=y;j++)//区间长度
{
dp[1][i+j]=min(dp[1][i+j],dp[0][i]+z[i+j]-z[i]);
dp[0][i+j]=min(dp[0][i+j],dp[1][i]+p[i+j]-p[i]);
}
}
cout<<min(dp[1][y1],dp[0][y1])<<endl;
}