均分纸牌问题

1536. 均分纸牌 - AcWing题库

x[i]代表i向i+1移动的牌数,负数时代表i+1向i移动

由于每次移动可以移动若干张牌,问移动几次,所以我们只需要看x[1]~x[n-1]中非零的个数。


#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
const int N = 100;
int a[N], sum[N], c[N];
int n;
int get()
{
    for(int i = 1; i <= n; i++) sum[i] = sum[i - 1] + a[i];
    int avg = sum[n] / n;
    int res = 0;
    for(int i = 1; i <= n - 1; i++) {
        c[i] = sum[i] - i * avg;
        if(c[i] != 0) res ++;
    }
    return res;
}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    cin >> n;
    for(int i = 1; i <= n; i++) cin >> a[i];

    cout << get() << endl;    

    return 0;
}

环形均分纸牌问题:

105. 七夕祭 - AcWing题库

这题和上题不大一样,每次移动只能移动一个,问移动次数。并且行和列都要均分,但是行内交换不会影响到列,列内交换也不会影响到行,所以我们分别进行两次环形均分纸牌操作就行了。

最后就转换成了一个经典问题:给你一组点的位置,求某个位置到所有点的距离最小是多少,最小值就是(所有点到其中位数的距离之和)


#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
#define int long long
const int N = 1e5 + 100;
int row[N], col[N], sum[N], c[N];
int n, m, t;
int get(int x, int a[])
{
    for(int i = 1; i <= x; i++) sum[i] = sum[i - 1] + a[i];
    if(sum[x] % x) return -1;
    int avg = sum[x] / x;
    c[1] = 0;
    for(int i = 2; i <= x; i++) c[i] = sum[i - 1] - (i - 1) * avg;
    sort(c + 1, c + 1 + x);
    int res = 0;
    for(int i = 1; i <= x; i++) res += abs(c[i] - c[(x + 1) / 2]);
    return res;
}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    cin >> n >> m >> t;
    while(t--)
    {
        int x, y;
        cin >> x >> y;
        row[x]++; col[y]++;
    }    
    int r = get(n, row);
    int c = get(m, col);
    if(~r && ~c) cout << "both" << " " << r + c << endl;
    else if(~r) cout << "row" << " " << r << endl;
    else if(~c) cout << "column" << " " << c << endl;
    else cout << "impossible" << endl;

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值