[贪心] aw3769. 移动石子(模拟)

1. 题目来源

链接:3769. 移动石子

2. 题目解析

贪心即可。

从左到右往第一个盒子走就行了,盒子下标从 0 开始,第 i 个盒子的一个石头走到第 0 个盒子需要操作 i 次。d/i 就是能操作过去的石头数量:

  • 如果 a[i]<=d/i 说明当前第 i 个盒子中的石头能全部移动到第一个盒子中。
  • 如果 a[i]>d/i 即第 i 个盒子中的石头只有 d/i 个石头能移动到第一个盒子中。

也可以不用存,直接边读入边计算即可。但是一定要注意:多组测试数据不要break,后面的还没读完


时间复杂度: O ( n ) O(n) O(n)

空间复杂度: O ( n ) O(n) O(n)


模拟

#include <bits/stdc++.h>

using namespace std;

const int N = 105;

int n, d;
int a[N];

int main() {
    int T; cin >> T; while (T -- ) {
        cin >> n >> d;
        for (int i = 0; i < n; i ++ ) cin >> a[i];
        
        int res = a[0];
        for (int i = 1; i < n; i ++ ) {
            int t = a[i] * i;
            if (d >= t) res += a[i], d -= t;
            else {
                res += d / i;
                break;
            }
        }
        
        cout << res << endl;
    }
    
    return 0;
}

y总的简洁风:

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

int main()
{
    int T;
    cin >> T;
    while (T -- )
    {
        int n, d;
        cin >> n >> d;
        int res = 0;
        for (int i = 0; i < n; i ++ )
        {
            int x;
            cin >> x;
            if (!i) res += x;
            else
            {
                int t = min(x, d / i);		// 不足的 d/i=0 就不用特判了
                res += t;
                d -= t * i;
            }
        }
        cout << res << endl;
    }

    return 0;
}

经典错误:多组测试数据不要break,后面的还没读完

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n,m,res,x;
        cin>>n>>m>>res;
        for(int i=1;i<n;++i)
        {
            cin>>x;
            /*int t=min(x,m/i);
            res+=t;
            m-=t*i;*/
            while(i*x>m)x--;
            res+=x;
            m-=x*i;
            if(m<=0)break;
        }
        cout<<res<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Ypuyu

如果帮助到你,可以请作者喝水~

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

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

打赏作者

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

抵扣说明:

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

余额充值