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
題意:給你一個由兩種顏色組成的圖,讓你進行染色,要求染色完成的圖滿足每列顏色相同,每行的顏色至少連續x種顏色的相同且連續相同顏色數小於等於
y,求最少的染色次數。
思路:先統計每列顏色爲"#"或"."的染色次數,用dp1[i][1]表示前i列滿足條件(且第i列爲“#”,dp[i][0]對應)的最少染色數,
dp1[i][1]=min(dp1[i][1],dp1[i-k][0]+dp[i][0]-dp[i-k][0]),dp1[i]表示第i列每列顏色滿足要求的染色次數.
代碼:
<pre name="code" class="cpp">#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
#define inf 9999999
char ma[1005][1005];
int dp[1005][2],dp1[1005][2];
int main()
{
int n,m,x,y;
while(scanf("%d%d%d%d",&n,&m,&x,&y)!=EOF)
{
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;i++)
{
scanf("%s",ma[i]+1);
}
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
if(ma[j][i]=='#')
dp[i][1]++;
else
dp[i][0]++;
}
}
dp[0][0]=0;
dp[0][1]=0;
for(int i=1;i<=m;i++)
{
dp[i][0]=dp[i-1][0]+dp[i][0];//統計前i列‘.’的個數
dp[i][1]=dp[i-1][1]+dp[i][1];//統計前i列'#'的個數
}
for(int i=1;i<=m;i++)
{
dp1[i][0]=inf;
dp1[i][1]=inf;
}
dp1[0][0]=0;
dp1[0][1]=0;
for(int i=1;i<=m;i++)
{
for(int k=x;k<=y;k++)
{
if(i-k>=0)
{
dp1[i][0]=min(dp1[i-k][1]+dp[i][1]-dp[i-k][1],dp1[i][0]);//第i列爲‘.’且滿足要求的最小染色次數
dp1[i][1]=min(dp1[i-k][0]+dp[i][0]-dp[i-k][0],dp1[i][1]);
}
}
}
printf("%d\n",min(dp1[m][1],dp1[m][0]));
}
return 0;
}