map容器是个好东西

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;
}
相关推荐
阿旭超级学得完1 小时前
C++11包装器(function和bind)
java·开发语言·c++·算法·哈希算法·散列表
li星野1 小时前
位运算 & 数学 & 高频进阶九题通关(Python + C++)
c++·python·学习·算法
jerryinwuhan1 小时前
hello算法,简单讲(1)
算法·排序算法
y = xⁿ1 小时前
20天速通LeetCodeday15:BFS广度优先搜索
算法·宽度优先
400分1 小时前
吃透RAG核心-----语义检索与关键字检索底层原理
算法·架构
目黑live +wacyltd1 小时前
算法备案:常见驳回原因与应对策略
人工智能·算法
磊 子2 小时前
多态类原理+四种类型转换+异常处理
开发语言·c++·算法
染指11103 小时前
3.AI大模型-token是什么-大模型底层运行机制
人工智能·算法·机器学习
谙弆悕博士3 小时前
快速学C语言——第19章:C语言常用开发库
c语言·开发语言·算法·业界资讯·常用函数
光影少年3 小时前
前端算法题
前端·javascript·算法