七夕祭
思路:对于本体行列互换时的性质可以发现:行与行之间的交换不影响列方向上的数量,反之同理,二者是相互独立的,因此可以分开解决这两个问题:
这里以行之间的交换(即列方向)为例:交换的目的是为了使同一列上的数都是相等的。首尾相连的特性确定这是一个环形纸牌均分问题
具体做法与另一题 糖果传递(https://www.acwing.com/problem/content/124/)几乎一样,可以先完成该题,具体题解参考自:(https://www.acwing.com/solution/content/41677/),这位写的很好
ac代码:
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e5 + 5;
int n, m, t;
int row[N], col[N];
int solve(int a[], int k){
int sum = 0;
for(int i = 1; i <= k; i ++) sum += a[i];
int ave = sum / k;
if(sum % k) return -1;
int s[N];
for(int i = 1; i <= k; i ++){
s[i] = s[i - 1] + a[i] - ave;
}
sort(s + 1, s + 1 + k);
int mid = s[(1 + k) / 2];
int res = 0;
for(int i = 1; i <= k; i ++) res += abs(mid - s[i]);
return res;
}
signed main(){
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n >> m >> t;
for(int i = 1; i <= t; i ++){
int x, y;
cin >> x >> y;
row[x] ++, col[y] ++;
}
int x1 = solve(row, n);
int x2 = solve(col, m);
if(x1 == -1 && x2 == -1) cout << "impossible" << '\n';
else if(x1 != -1 && x2 != -1) cout << "both " << x1 + x2 << '\n';
else if(x1 == -1) cout << "column " << x2 << '\n';
else if(x2 == -1) cout << "row " << x1 << '\n';
return 0;
}