P1102 A-B 数对 - 洛谷


这道题明显不能暴力
这一题将A-B=C转换成A-C=B,将a数组每个元素的次数存在map容器中,b[i]=a[i]-c,b[i]在map容器中出现,将次数加起来,就是数对的个数
cpp
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=2e5+5;
LL a[N],b[N];
map<LL,LL> m;
int main(){
int n;
LL c;
LL ans=0;
cin>>n>>c;
for(int i=0;i<n;i++){
cin>>a[i];
m[a[i]]++;
b[i]=a[i]-c;
}
for(int i=0;i<n;i++) ans+=m[b[i]];
cout<<ans;
return 0;
}
P5250 【深基17.例5】木材仓库 - 洛谷

先"假装"存一下该不存在的木头,然后指针定位该木头的位置
it2:指向y本身
it:指向比y大的第一个元素
--it2:指向比y小的第一个元素
cpp
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int main(){
map<int,int>mp;
LL x,y;
int m;
cin>>m;
while(m--){
cin>>x>>y;
if(x==1){
if(mp.count(y)) cout<<"Already Exist"<<endl;
else mp[y]=1;
}
else{
if(mp.empty()) cout<<"Empty"<<endl;
else if(mp.count(y)){
mp.erase(y);
cout<<y<<endl;
}
else{
mp[y]=1;
auto it=mp.find(y);
auto it2=it;
it++;
if(it2==mp.begin()){
cout<<it->first<<endl;
mp.erase(it);
}
else if(it==mp.end()){
cout<<(--it2)->first<<endl;
mp.erase(it2);
}
else if(y-(--it2)->first>it->first-y){
cout<<it->first<<endl;
mp.erase(it);
}
else{
cout<<it2->first<<endl;
mp.erase(it2);
}
mp.erase(y);
}
}
}
return 0;
}