USACO历年青铜组真题解析 | 2023年2月Hungry Cow

学习C++从娃娃抓起!记录下USACO(美国信息学奥赛)备考青铜组别比赛学习过程中的题目,记录每一个瞬间。

附上汇总贴:USACO历年青铜组真题解析 | 汇总-CSDN博客


【题目描述】

Bessie 喜欢吃干草。每一天晚上,如果她所在的谷仓里面还有至少一堆干草,Bessie 都会吃一堆当作晚饭。

一开始谷仓里面并没有任何干草,为了不让 Bessie 饿着,FJ 会时不时地给 Bessie 送干草。具体来说,他会在第 di 天给 Bessie 送来 bi 堆干草,并总共送 N 次。(1≤N≤10^5,1≤di≤10^14,1≤bi≤10^9)。

Bessie 想要知道在前 T 天她一共能吃多少堆干草,请你帮助她算出这个数值。(1≤T≤10^14)

请注意数据范围,可能需要使用 long long 来存储部分数据。

【输入】

The first line contains N and T (1≤N≤10^5,1≤T≤10^14).

The next N lines each contain di and bi. It is additionally guaranteed that 1≤d1<d2<⋯<dNT.

【输出】

Output the number of haybales that Bessie will eat during the first T days.

Note that the large size of integers involved in this problem may require the use of 64-bit integer data types (e.g., a "long long" in C/C++).

【输入样例】

1 5
1 2

【输出样例】

2

【代码详解】

#include <bits/stdc++.h>
using namespace std;
int n;
long long t, nowd, nowb, lastd, lastb, ans=0;
int main()
{
    cin >> n >> t;  // 输入n和t
    cin >> lastd >> lastb;  // 输入第i天,以及干草堆数,将其标记为last,后面循环每次都需要和前一天进行比较
    if (n==1) {  // 特判n为1,直接输出干草堆数
        cout << lastb << endl;
        return 0;
    }
    for (int i=2; i<=n; i++) {  // for循环遍历之后n-1次
        cin >> nowd >> nowb;  // 输入第i天,以及这天的干草堆数
        if (nowd<t) {  // 如果这一天比询问的t天小
            if ((nowd-lastd)>lastb) {  // 则判断与上次的天数之差大于干草堆数
                ans += lastb;  // 说明干草不够相差的这么多天每天吃,只能吃之前的干草堆数
                lastb = nowb;  // 更新lastb和lastd
                lastd = nowd;
            } else {  // 如果与上次的天数之差小于等于干草堆数
                ans += (nowd-lastd);  // 则吃了这么多天的干草
                lastb = lastb - (nowd-lastd) + nowb;  // 剩余的干草要添加到lastb中
                lastd = nowd;  // 更新lastd
            }
        }
        else if (nowd==t) {  // 如果输入的天数为t天
            if ((nowd-lastd)>lastb) {  // 同样判断与上次的天数之差大于干草堆数
                ans += lastb;  // 说明干草不够相差的这么多天每天吃,只能吃之前的干草堆数
                ans += 1;  // 第t天还需要再吃一堆
                cout << ans << endl;  // 输出结果
                return 0;  // 并退出程序
            } else {  // 如果与上次的天数之差小于等于干草堆数
                ans += (nowd-lastd);  // 则吃了这么多天的干草
                ans += 1;  // 同样第t天需要再吃一堆
                cout << ans << endl;  // 输出结果
                return 0;  // 并退出程序
            }
        }
    }
    if (t>lastd) {  // 如果t大于n次数的最后一天,则一样要做判断
        if ((t-lastd)>lastb) {  // 如果与上次的天数之差大于干草堆数
            ans += lastb;  // 说明只能吃之前的干草堆数
        } else {  // 如果小于等于干草堆数
            ans += (t-lastd)+1;  // 则吃了相差天数+1的干草
        }
    }
    cout << ans << endl;  // 输出结果
    return 0;
}

【运行结果】

1 5
1 2
2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值