本文分享的必刷题目是从蓝桥云课、洛谷、AcWing等知名刷题平台精心挑选而来,并结合各平台提供的算法标签和难度等级进行了系统分类。题目涵盖了从基础到进阶的多种算法和数据结构,旨在为不同阶段的编程学习者提供一条清晰、平稳的学习提升路径。
欢迎大家订阅我的专栏:算法题解:C++与Python实现!
附上汇总贴:算法竞赛备考冲刺必刷题(C++) | 汇总
【题目来源】
洛谷:P2969 [USACO09DEC] Music Notes S - 洛谷
【题目描述】
约翰准备教他的奶牛们弹一首歌。这首歌由 N 个音阶组成,第 i 个音阶要敲击 Bi 次。奶牛从第 0 时刻开始弹,因此他从 0 时刻到 Bi−1 时刻都是敲第 1 个音阶,然后他从 B1 时刻到 B1+B2−1 时刻敲第 2 个音阶,从 B1+B2 到 B1+B2+B3−1 时刻敲第 3 个音阶……现在有 Q 个问题:在时间段区间 T,T+1 内,奶牛敲的是哪个音阶?
1≤N≤50000,1≤Q≤50000,1≤Bi≤10000。
【输入】
- Line 1: Two space-separated integers: N and Q
- Lines 2…N+1: Line i+1 contains the single integer: B_i
- Lines N+2…N+Q+1: Line N+i+1 contains a single integer: T_i
【输出】
- Lines 1…Q: For each =-098765query, print a single integer that is the index of the note that the cows should be playing.
【输入样例】
3 5
2
1
3
2
3
4
0
1
【输出样例】
2
3
3
1
1
【解题思路】
【算法标签】
《洛谷 P2969 Music Notes》 #排序# #前缀和# #USACO# #2009#
【代码详解】
#include <bits/stdc++.h>
using namespace std;
int n, q, a[50005],b[50005];
int main()
{
cin >> n >> q; // 输入n和q
for (int i=1; i<=n; i++) {
int tmp;
cin >> tmp;
a[i] = a[i-1]+tmp; // 使用前缀和记录
}
for (int i=1; i<=q; i++) { // 记录q个问题
cin >> b[i];
}
for (int i=1; i<=q; i++) { // 遍历q个问题
int x = b[i];
int l=1, r=n; // 二分搜索模板
while (l<=r) {
int mid = l + (r-l)/2;
if (a[mid]<=x) { // 当mid对应的值小于等于x
l = mid+1; // 左指针右移至mid+1
} else r = mid-1; // 否则右指针左移至mid-1
}
cout << l << endl; // (输出什么感觉就是个玄学,正常先移动左指针,最后输出的就是r,这里输出l)
}
return 0;
}
【运行结果】
3 5
2
1
3
2
3
4
0
1
2
3
3
1
1