Daimayuan订单编号(set/并查集)

题目链接:http://oj.daimayuan.top/problem/465
题意:给定n个整数,对于每个数你需要输出前面没有出现过的且大于等于它本身的最小正整数。

样例输入:
6
2 3 4 1 1 1

样例输出
2 3 4 1 5 6

代码:
set<pair<int,int> >

#include<bits/stdc++.h>
using namespace std;

set<pair<int,int> >s;
//用set维护一些可行区间

void myinsert(int l,int r){
    if(l>r) return;
    s.insert({r,l});
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    int n;
    cin>>n;
    s.insert({2e9, 1});
    
    for(int i=0;i<n;i++){
        int x;
        cin>>x;
        auto it = s.lower_bound({x,0});//找到大于x的最近的一个可行区间
        int l = it->second, r = it->first;//可行区间的端点
        s.erase(it);
        if(x>l){//x在可行区间中间,不包括左端点
            cout<<x<<" ";
            myinsert(l,x-1);
            myinsert(x+1,r);
        }
        else{//x在可行区间左边,包括左端点
            cout<<l<<" ";
            myinsert(l+1,r);
        }
    }
    return 0;
}

并查集
用并查集来维护,x能达到的下一个位置

#include<bits/stdc++.h>
using namespace std;

const int N = 5e5+5;

unordered_map<int,int>f;

//用并查集来维护一个数x能放的位置
long long find(int x){
    return f.count(x)==0 ? x : f[x] = find(f[x]);
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    int n;
    cin>>n;
    for(int i=0;i<n;i++){
        int x;
        cin>>x;
        //把这个数放到这个位置后,找到x下一次能到达的位置
        int fx = find(x);
        cout<<fx<<" ";
        f[fx] = fx + 1;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值