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; }