题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1735
题目解析:
先不考虑段落个数M的限制,只要可能是分段就分段,统计出最少缺失字数,然后看实际段落数X 如果大于M, 增加 X-M个段落缺失的字数(按段落间空格个数从少到多挑选)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int art[10000][100];
int emptyTail[10000];
int compare(const void *a, const void *b) { return *(int *)b - *(int *)a; }
int main() {
int N, L, M;
while (scanf("%d %d %d", &N, &L, &M) != EOF) {
memset(art, 0, sizeof(art));
memset(emptyTail, -1, sizeof(emptyTail));
for (int i = 0; i < N; i++) {
for (int j = 0; j < L; j++) {
scanf("%d", &art[i][j]);
}
}
int lackNum = 0;
for (int i = 0; i < N; i++) {
int zero = 1; //是否可能是段落最后一行空白
if (i < N - 1) {
zero = !(art[i + 1][0] || art[i + 1][1]);
}
for (int j = L - 1; j >= 0; j--) {
if (art[i][j] == 0) {
if (!zero && j > 1) {
art[i][j] = 1;
lackNum++;
}
if (j == 1 && art[i][0] != 0) {
art[i][j] = 1;
lackNum++;
}
if (j == 0 && art[i][1] != 0) {
art[i][j] = 1;
lackNum++;
}
} else {
zero = 0;
}
}
}
int passages = 1;
for (int i = 1; i < N; i++) {
if (art[i][0] == 0) {
passages++;
emptyTail[i - 1] = 0;
for (int j = L - 1; j >= 0; j--) {
if (art[i - 1][j] == 0) {
emptyTail[i - 1]++;
} else {
break;
}
}
}
}
if (passages > M) {
qsort(emptyTail, N, sizeof(emptyTail[0]), compare);
for (int i = M - 1; i < N; i++) {
if (emptyTail[i] > -1) {
lackNum += (2 + emptyTail[i]);
}
}
}
printf("%d\n", lackNum);
}
}