2025.11.14课程题目解析+总结
题目解析+总结
B4362 eqal_range
分析题干+步骤书写
要找第一个比大的数,并找一个比小的数,就是一个二分答案。 先用upper_bound在序列中找第一个比大的数,下标为。若,则不存在这个数。 再用lower_bound在序列中找第一个比大或等于的数,则前面的一个数一定比小,这个数的下标就为。若也同理。 时间优化:
- 输入输出关闭同步流
- 换行endl改为”\n”
AC代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
map<int,int>vis;
int maxx = 0,id = 0,n;
signed main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin>>n;
for(int i=1;i<=n;++i){
int a; cin>>a;
if(maxx == 0) id = a,maxx++;
else if(a != id) maxx--;
else maxx++;
}
cout<<id<<endl;
return 0;
}P2397 yyy loves Maths VI (mode) / 摩尔投票
分析题干+步骤书写
最终哪个阵营会赢,取决于哪个阵营的人更多,找众数,就是把数组分成两个部分,一部分是众数,另一部分是其他数字。 每一次都删除两个数字,剩下的一定是众数,因为众数是数组的一半多。
AC代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,q,a[1000005];
signed 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 = lower_bound(a+1,a+1+n,x) - a;
int pos2 = upper_bound(a+1,a+1+n,x) - a;
if(pos2 > n) cout<<-1<<' ';
else cout<<a[pos2]<<' ';
if(pos-1 < 1) cout<<-1<<"\n";
else cout<<a[pos-1]<<"\n";
- [ ] }
return 0;
}T692642 [THUPC 2017] 玩游戏
分析题干+步骤书写
一共有轮游戏,第轮获胜者会得到分,每一轮不会出现平局。 给定ljcc和学妹的得分,问是否存在一种比赛方案满足条件,也即是我们要找出游戏一共进行了多少论,每一轮到底是谁获胜,如果有多种结果输出任意一种即可。 因为第轮获得分,那么如果有轮,总分为 。若ljcc得分是,学妹得分是。 那么可以推出 ,化简可得 。
AC代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
signed main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int a,b,n;
cin>>a>>b;
int l = 0,r = 2*(a+b)+1,id = -1e9;
while(l + 1 < r){
int mid = (l+r)/2,pos = mid*mid+mid;
if(pos == 2*(a+b)){
id = mid;
break;
}
else if(pos > 2*(a+b)) r = mid;
else l = mid;
}
if(id == -1e9){
cout<<"No\n";
return 0;
}
cout<<id<<' ';
for(int i=id;i>=1;--i){
if(a >= i){
cout<<i;
a -= i;
if(a != 0) cout<<' ';
}
}
return 0;
}T692642 [海淀区小学组 2025] 蜂窝网络
分析题干+步骤书写
有个城市,个信号塔,每个城市的坐标是,每个信号塔的坐标是。 如果信号覆盖范围是,那么第个信号塔的信号就能覆盖 ~ 我们要找到最小的,使得每一个城市都被信号覆盖。 我们可以发现单调性:越大,那么信号塔能够覆盖的范围就越广,那么覆盖所有城市的概率就越大。我们使用二分答案查找的最小值。 二分答案之后,要判断每一个城市是否被信号覆盖。 就是去找到离城市最近的信号塔,判断离城市最近的信号塔离这个城市的距离是否小于等于mid。
AC代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m,a[100005],b[100005];
bool check(int mid){
b[m+1] = 1e18,b[0] = -1e18;
for(int i=1;i<=n;++i){
int pos = lower_bound(b+1,b+1+m,a[i]) - b;
if(b[pos] - a[i] > mid && a[i] - b[pos-1] > mid) return 0;
}
return 1;
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;++i) cin>>a[i];
for(int i=1;i<=m;++i) cin>>b[i];
sort(a+1,a+1+n),sort(b+1,b+1+m);
int l = 0,r = 2e9+1;
while(l+1 < r){
int mid = (l+r) / 2;
if(check(mid)) r = mid;
else l = mid;
}
cout<<r<<endl;
return 0;
}