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;
}
相关推荐
郝学胜-神的一滴2 小时前
张量维度操控心法:从reshape到升维降维,吃透PyTorch形状操作的底层逻辑
人工智能·pytorch·python·深度学习·程序人生·算法·机器学习
果果燕3 小时前
ARM嵌入式学习(四)--- C语言应用:led、beep、key
linux·运维·算法
Q741_1473 小时前
每日一题 力扣 2751.机器人碰撞 映射 模拟 栈 C++ 题解
算法·leetcode·模拟··映射
源码之家3 小时前
计算机毕业设计:基于Python的二手车数据分析可视化系统 Flask框架 可视化 时间序列预测算法 逻辑回归 requests 爬虫 大数据(建议收藏)✅
大数据·hadoop·python·算法·数据分析·flask·课程设计
liuyao_xianhui3 小时前
优选算法_岛屿数量_floodfill算法)_bfs_C++
java·开发语言·数据结构·c++·算法·链表·宽度优先
羊小蜜.3 小时前
Mysql 04: 子查询——5 大核心用法
数据库·mysql·算法·子查询
小碗羊肉3 小时前
【数据结构】红黑树(Red-Black Tree)
数据结构
深邃-3 小时前
字符函数和字符串函数(2)
c语言·数据结构·c++·后端·算法·restful
bekote3 小时前
PTA基础编程题目集-6-11 求自定类型元素序列的中位数(简单解法)
数据结构·c++·算法