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;
}
相关推荐
lihihi10 小时前
P9936 [NFLSPC #6] 等差数列
算法
啊我不会诶10 小时前
2024ICPC西安邀请赛补题
c++·算法
谭欣辰11 小时前
C++ 版Dijkstra 算法详解
c++·算法·图论
yuan1999711 小时前
C&CG(列与约束生成)算法,来解决“风光随机性”下的微网鲁棒配置问题
c语言·开发语言·算法
数智化精益手记局11 小时前
人员排班管理软件的自动化功能解析:解决传统手工人员进行排班管理耗时长的难题
运维·数据结构·人工智能·信息可视化·自动化·制造·精益工程
wayz1111 小时前
Day 11 编程实战:XGBoost金融预测与调参
算法·机器学习·金融·集成学习·boosting
念越11 小时前
算法每日一题 Day07|双指针求解和为S的两个数
算法·力扣
LeocenaY11 小时前
C语言面试题总结
c语言·开发语言·数据结构
qeen8711 小时前
【算法笔记】双指针及其经典例题解析
c++·笔记·算法·双指针
黎阳之光11 小时前
黎阳之光:以视频孪生+全域感知,助力低空经济破局突围
大数据·人工智能·算法·安全·数字孪生