P5534 【XR-3】等差数列
题意:
- 给出一个等差数列的前两项和项数,输出整个等差数列的和
思路:
- 首先求出公差d=a2−a1,然后就可以一一枚举出a3 ~ an的每一个数字了,最后将每一个数字相加即可
代码:
C++#include<bits/stdc++.h>
#define int long long
using namespace std;
int a[1000005];
int d, n;
char c;
int sum;
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> a[1]>> a[2]>> n;
sum += a[1] + a[2];
d = a[2] - a[1];
for(int i = 3;i <= n;i++){
a[i] = a[i - 1] + d;
sum += a[i];
}
cout << sum;
return 0;
}
错因:
- #define int long long写成了#define long long int,且没使用signed main()
B4362 eqal_range
题意:
- 给出一个长度为n的序列a,然后有q次询问,每次询问包括一个整数x,请分别输出序列a里最小的比x大的数是多少?a里最大的比x小的数是多少?如果没有这样的数字,输出−1
思路:
- 可以使用二分查找右侧边界大于x的最小值,二分查找左侧边界小于x的最大值,如果发现对应的值没有查到,就输出−1
代码:
C++#include<bits/stdc++.h>
#define long long int
using namespace std;
int n, q;
int a[1000005];
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n>> q;
for(int i = 1;i <= n;i++){
cin >> a[i];
}
sort(a + 1, a + 1 + n);
while(q--){
int x;
cin >> x;
int pos = upper_bound(a + 1, a + 1 + n, x) - a;
if(pos == n + 1){
cout << -1;
}else{
cout << a[pos];
}
cout << ' ';
pos = lower_bound(a + 1, a + 1 + n, x) - a - 1;
if(pos == 0){
cout << -1;
}else{
cout << a[pos];
}
cout << '\n';
}
return 0;
}
错因:
- O(q∗n),数据过大已经超时
P1830 轰炸III
题意:
- 有一座大小为n∗m的城市,将遭受x次轰炸,每次输入了坐标x1 y1 x2 y2,指挥官想知道y个坐标是否遭到了轰炸,有输出Y,以及被炸了几次和最后一次是第几轮,否则输出N
思路:
- 可以依次枚举每一个坐标x1 <= x <= x2并y1 <= y <= y2数组a的地方+1,并用另一个数组b来记录这里最后一轮的轰炸,询问时只要判断bxy的位置是否有记录就行,输出对应的结果就可以了
代码:
C++#include<bits/stdc++.h>
using namespace std;
int n, m, x, y;
int a[105][105], b[105][105];
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n>> m>> x>> y;
for(int t = 1;t <= x;t++){
int x1, y1, x2, y2;
cin >> x1>> y1>> x2>> y2;
for(int i = x1;i <= x2;i++){
for(int j = y1;j <= y2;j++){
a[i][j]++;
b[i][j] = t;
}
}
}
while(y--){
int x, y;
cin >> x>> y;
if(a[x][y] == 0){
cout << 'N'<< '\n';
}else{
cout << 'Y'<< ' '<< a[x][y]<< ' '<< b[x][y]<< '\n';
}
}
return 0;
}
错因:
P12344 [蓝桥杯 2025 省 B/Python B 第二场] 破解信息
题意:
- 给出一个字符串S,找出S中字典序最大的回文子序列
- 字典序比较:先比较第一个字符、然后比较第二个字符…,如果所有字符都相等,最终比较长度。 字典序大小不是直接根据字符串长度来决定的
思路:
- 想要子序列字典序最大,那么应该使得第一个字符最大,因为这个是需要回文子序列,我们字符串末尾添加的字符必须和前面的字符相等,因为没有限制子序列一定相连接,所以我们只会选择最大的字符输出
代码:
C++#include<bits/stdc++.h>
using namespace std;
string s;
int main(){
cin >> s;
int maxn = 0;
for(int i = 0;i < s.size();i++){
maxn = max(maxn, int(s[i]));
}
for(int i = 0;i < s.size();i++){
if(int(s[i]) == maxn){
cout << s[i];
}
}
return 0;
}
错因: