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 分钟前
数据结构( Floyd)
数据结构·算法
金榜题名萱21 分钟前
蓝桥杯 - 妮妮的月饼工厂(二分)
c语言·数据结构·c++·算法·蓝桥杯·动态规划
小王C语言1 小时前
优选算法:队列+宽选(bfs)
数据结构·算法·宽度优先
HQL_seven2 小时前
【数据结构】线性结构
数据结构
AI殉道师2 小时前
合因科技三大临床试验数字化模块:EDC + RTSM(IWRS)+ ePRO,从入组到随访如何协同?
科技·算法·临床试验数字化
龙砚序2 小时前
【数据结构|二叉树实战 05-1】文件系统目录树构建与统计模块(C 语言递归实现)
数据结构
Shaoshing2 小时前
LeetCode100 76.最小覆盖字串
java·算法·leetcode
不知棋者3 小时前
蓝桥杯 2020 省赛 B 组既约分数:从暴力枚举到欧拉函数前缀和
c++·算法·职场和发展·蓝桥杯
电科_银尘3 小时前
【大模型算法与工程 63】视觉语言模型:视觉编码器如何接入LLM
人工智能·算法·语言模型
小蒋学算法3 小时前
算法-三个无重叠子数组的最大和-前缀和+前缀和最值维护
数据结构·算法