map容器是个好东西

P1102 A-B 数对 - 洛谷

这道题明显不能暴力

这一题将A-B=C转换成A-C=B,将a数组每个元素的次数存在map容器中,bi=ai-c,bi在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;
}
相关推荐
普通攻击往后拉18 小时前
Leetcode 206. 反转链表
算法·leetcode·链表
@syh.18 小时前
【贪心】矩阵消除游戏
算法·游戏·矩阵
可编程芯片开发19 小时前
基于零极点配置的PID控制系统simulink建模与仿真
算法
徐小夕19 小时前
开源!我用SQLite + DuckDB打造了一款可视化AI问数平台
前端·算法·github
Hrain-AI19 小时前
2026 企业 AI 智能体平台横评:8 大主流平台 7 维度实测对比
人工智能·算法·机器学习
Angel Q.20 小时前
因子分析和生成模型有什么关系?从“幕后因素”到“生成数据”
算法
FBI HackerHarry浩21 小时前
AI大模型开发V2第四阶段线性回归
人工智能·算法·线性回归
Jerry1 天前
LeetCode 108. 将有序数组转换为二叉搜索树
算法
蓝斯4971 天前
Diff算法的简单介绍
算法