思路
将该问题转化成环形均分纸牌问题和货仓选址问题。
行和列并不互相影响,完全可以分开计算,每一行或一列都是一个环行均分纸牌问题。
证明
推导过程
跟着大佬一步一步推导公式,一次不懂多看几遍就很容易了。
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
const int N = 100010;
typedef long long ll;
ll a[N],b[N];
ll get(ll *c, int n){
int avg = 0;
for(int i = 1; i <= n; i++) avg += c[i];
avg /= n;
c[1] = 0;
for(int i = 2; i <= n; i++) c[i] = c[i-1]+c[i]-avg;
sort(c+1,c+1+n);
ll res = 0, mid = c[n/2+1]; //+1是为了保证n为奇数时取到中间的数,偶数无所谓左右
for(int i = 1; i <= n; i++) res += abs(c[i]-mid);//根据货仓选址问题可知选取中位数会使结果最小
return res;
}
int main(){
cin.tie(0)->sync_with_stdio(false);
int n,m,k;
cin>>n>>m>>k;
for(int i = 0; i < k; i++){
int x,y; cin>>x>>y;
a[x]++, b[y]++;
}
if(k % n && k % m) puts("impossible");
else if(k % n) printf("column %lld",get(b,m)); //列可以整除
else if(k % m) printf("row %lld",get(a,n)); //行可以整除
else printf("both %lld",get(a,n)+get(b,m));
return 0;
}