题目:P1918 保龄球 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
截取部分题目要素:
-
◯◯◯
-
◯◯◯ ◯
-
◯
-
◯ ◯
如上图,每个 “◯” 代表一个瓶子。如果 DL 想要打倒 3 个瓶子就在 1 位置发球,想要打倒 4 个瓶子就在 2位置发球。
现在他想 打倒 m 个瓶子。他告诉你每个位置的瓶子数,请你给他一个发球位置。
看着得map根据key元素value
上代码
#include<bits/stdc++.h>
using namespace std;
map<int,int>ma;//细心观察,耐心
int n,a,q,m;
int main(){
cin>>n;
for(int i=1;i<=n;i++){
cin>>a;
ma[a]=i;
}
cin>>q;
for(int i=1;i<=q;i++){
cin>>m;
cout<<ma[m]<<endl;
}
return 0;
}
扩展A-B=C开始
题目:P1102 A-B 数对 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
还是map映射?可以用,这是方法一,看代码:
#include<bits/stdc++.h>
using namespace std;
//用map映射 ,将a数组每个元素出现次数统计,m[a[i]]++;a数组每次减c,再遍历,相加使用映射次数
typedef unsingned long long ull;//用long long也行
ull a[200001];
map<ull,ull>m;//a-c=b;
int main(){
ull n,c,ans=0;
cin>>n>>c;
for(int i=1;i<=n;i++){
cin>>a[i];
m[a[i]]++;
a[i]-=c;
}
for(int i=1;i<=n;i++){
ans+=m[a[i]];
}
cout<<ans;
return 0;
}
方法二·:用upper_bound, lower_bound (不了解再查阅资料)
玄学了
//upper_bound,a[]i+c后面第一个大于的数,lower_bound,后面第一个大于等于的,因为排序了,
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
long long a[200000+5],ans=0;
int main(){
ull n,c;
cin>>n>>c;
for(int i=1;i<=n;i++){
cin>>a[i];
}
sort(a+1,a+n+1);
for(int i=1;i<=n;i++){
ans+=((upper_bound(a+1,a+n+1,a[i]+c)-a)-(lower_bound(a+1,a+n+1,a[i]+c)-a));//+c,a+c=b,ans为下标
}
cout<<ans;
return 0;
}
寄包柜问题,开二维map映射
题目:P3613 【深基15.例2】寄包柜 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
题目截取:
代码奉上,找和上面相似哦
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
map<int,map<int,int> > ma;//map二维映射,查询输出映射值
int main(){
int n,q,k,i,j;
cin>>n>>q;
while(q--){
cin>>k>>i>>j;
if(k==1){
int ty;
cin>>ty;
ma[i][j]=ty;
}
else{
cout<<ma[i][j]<<endl;
}
}
return 0;
}