七夕祭:分治+贪心+排序+前缀和+中位数

我们先来看一道简化版的

均分纸牌:

异曲同工之处,均分纸牌是一维的,并且空间是正常的。

首先判断可不可以均分纸牌,如果可以,为了使得第一堆纸牌可以均分,必须后面一堆纸牌拿牌层层递推。

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Shirandexiaowo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值