学习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<⋯<dN≤T.
【输出】
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