《算法竞赛进阶指南》书上已经给了完整的算法分析,那么我就给出本题标准的C++代码。
#include <bits/stdc++.h>
using namespace std;
int cols[100010], rows[100010];
long long s[100010];
int main(void) {
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
while (k--) {
int x, y;
scanf("%d%d", &x, &y);
++rows[x];
++cols[y];
}
long long res_row,
sum_row = 0;
for (int i = 1; i <= n; ++i) {
sum_row += rows[i];
}
if (sum_row % n == 0) {
for (int i = 1; i <= n; ++i) {
s[i] = s[i - 1] + rows[i] - sum_row / n;
}
sort(s + 1, s + n + 1);
res_row = 0;
for (int i = 1; i <= n; ++i) {
res_row += max(s[i] - s[(n + 1) / 2], s[(n + 1) / 2] - s[i]);
}
} else {
res_row = -1;
}
long long res_col,
sum_col = 0;
for (int i = 1; i <= m; ++i) {
sum_col += cols[i];
}
if (sum_col % m == 0) {
for (int i = 1; i <= m; ++i) {
s[i] = s[i - 1] + cols[i] - sum_col / m;
}
sort(s + 1, s + m + 1);
res_col = 0;
for (int i = 1; i <= m; ++i) {
res_col += max(s[i] - s[(m + 1) / 2], s[(m + 1) / 2] - s[i]);
}
} else {
res_col = -1;
}
if (res_row == -1 && res_col == -1) {
puts("impossible");
} else if (res_row == -1) {
printf("column %lld\n", res_col);
} else if (res_col == -1) {
printf("row %lld\n", res_row);
} else {
printf("both %lld\n", res_row + res_col);
}
return 0;
}