我们先来看一道简化版的
均分纸牌:
异曲同工之处,均分纸牌是一维的,并且空间是正常的。
首先判断可不可以均分纸牌,如果可以,为了使得第一堆纸牌可以均分,必须后面一堆纸牌拿牌层层递推。
#include <iostream>
using namespace std;
int n, sum, ans;
int a[110];
int main()
{
cin >> n;
for(int i = 1; i <= n; i++)
{
cin >> a[i];
sum += a[i];
}
int avg = sum / n;
for(int i = 1; i < n; i++)
{
if(a[i] != avg) a[i + 1] -= avg - a[i], ans++;
}
//cout << avg << endl;
cout << ans << endl;
return 0;
}
七夕祭:
首先,横向或者竖向移动不会改变另一个方向的纸牌我们只需要单独考虑行和列
这个空间扭曲了,因此不是简单的移动了,需要选择中位数作为参考的标志点。
我们假设空间没有扭曲的情况下,答案应该是前缀和数组的前缀和。
通过扭曲空间,需要找一个中心的位置,使得移动的次数最少,变成了仓库选址问题
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
const int N = 1e5 + 5;
#define ll long long
ll n, m, ans;
ll t;
ll x[N], y[N], f[N];
ll int calc(ll int a[N],int k)
{
ll avg = a[0] / k;
ll res = 0;
for(int i = 1; i <= k; i++)
{
a[i] -= avg;
f[i] = f[i - 1] + a[i];
}
sort(f + 1, f + k + 1);
for(int i = 1; i <= k; i++)
{
res += abs(f[i] - f[k + 1 >> 1]);
}
return res;
}
int main()
{
cin >> n >> m >> t;
for(int i = 1; i <= t; i++)
{
int a, b;
cin >> a >> b;
x[a]++;
y[b]++;
x[0]++;
y[0]++;
}
if(x[0] % n == 0 && y[0] % m == 0)
{
ans = calc(x, n) + calc(y, m);
cout << "both " << ans << endl;
}
else if(x[0] % n == 0)
{
ans = calc(x, n);
cout << "row " << ans << endl;
}
else if(y[0] % m == 0)
{
ans = calc(y, m);
cout << "column " << ans << endl;
}
else cout << "impossible" << endl;
return 0;
}