环形纸牌问题

1、均分纸牌
题意概括:
解题思路:可以分类讨论,先讨论1,n的情况,再从讨论[2,n-1]的情况。也可以直接遍历[1,n],如果a[i] != avg,那么a[i+1] += (a[i]-avg),ans++,对于这个式子的理解,如果a[i] > avg,那么需要向右传递,a[i] - avg为正数,反之需要向后一个索取,a[i]-avg为负数,达到了同时兼顾左边和右边,并且对于1和N,仅有一种情况。
代码:

#include <iostream>

using namespace std;

const int N = 110;

int a[N];
int n , total;
int ans;

int main()
{
    cin >> n;

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

    int avg = total / n;

    for(int i = 1 ; i <= n ; i++)
        if(a[i] != avg) a[i + 1] += a[i] - avg , ans++;

    cout << ans << endl;
    return 0;
}

2、糖果传递
题意概括:一个数组组成一个环,每次每个值可以向左右两边传递一个值,求最小次数。
解题思路:
在这里插入图片描述
代码:

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const int N = 1e6+10;
LL a[N];
int n;
LL s[N],c[N];
int main()
{
    cin >> n;
    LL sum = 0;
    for (int i = 1; i <= n; i ++ )
    {
        cin >> a[i];
        sum += a[i];
        s[i] = s[i-1] + a[i];
    }
    LL avg = sum/n;
    for (int i = 1; i <= n; i ++ )
    {
        c[i] = s[i-1] - (i-1) * avg;
    }
    
    sort(c+1,c+1+n);
    LL ans = 0;
    for (int i = 1; i <= n; i ++ )
    {
        ans += abs(c[i] - c[n/2+1]);
    }
    cout << ans << endl;
    return 0;
    
}

3、七夕祭
题意概括:本题在上一题的基础上增加了判断行列两种情况即可
代码:

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const int N = 100010;
int n,m,t;
int row[N],col[N];
LL s[N],c[N];
LL work(int n,int a[])
{
    LL sum = 0;
    for (int i = 1; i <= n; i ++ ) 
    {
        sum += a[i];
        s[i] = s[i-1] + a[i];
    }
    if(sum % n != 0) return -1;
    
    LL avg = sum / n;
    for (int i = 1; i <= n; i ++ )
    {
        c[i] = s[i-1] - (i-1)*avg;
    }
    
    sort(c+1,c+1+n);
    LL res = 0;
    for (int i = 1; i <= n; i ++ )
    {
        res += abs(c[i] - c[n/2+1]);
    }
    return res;
}
int main()
{
    cin >> n >> m >> t;
    while(t --)
    {
        int x,y;
        cin >> x >> y;
        row[x]++,col[y]++;
    }
    LL r = work(n,row);
    LL c = work(m,col);
    if(r != -1 && c != -1) cout << "both" << " " << r+c << endl;
    else if(r != -1) cout << "row" << " " << r << endl;
    else if(c != -1) 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、付费专栏及课程。

余额充值