Codeforces Round #834 (Div.3) G. Restore the Permutation

题意:

序列p为1~n排列的一种,数组b由序列p构造而成,𝑏𝑖=max(𝑝2𝑖−1,𝑝2𝑖) for 1≤𝑖≤𝑛/2。给定n和数组b,求字典序最小的序列p并输出;如果序列不存在,则输出-1。

思路:

先将b中元素填入ans,ans2𝑖=𝑏𝑖(1≤𝑖≤𝑛/2),从大到小遍历i(n~1)填数到ans中构造p序列,如果i在b中出现过则进队,没出现过则判断是否队空,若是则表示p序列不存在,否则取队头元素,该数为b数组中已遍历过的数在ans数组的位置的最大值,将i放入该数前一位置。

代码:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;

const int N = 200001;

int main() {
    int t, n;
    cin>>t;
    while(t--) {
        cin>>n;
        int ans[N] = {0}, b[N] = {0};
        bool flag = true;
        for(int i=2; i<=n; i+=2) {
            cin>>ans[i]; //填入ans
            b[ans[i]] = i; //记录位置
        }
        priority_queue<int> q;
        for(int i=n; i>0; i--) {
            if(b[i])
                q.push(b[i]); //i在b中进队
            else {
                if(q.empty()) { //不满足ans2i=bi(1≤i≤n/2)
                    flag = false;
                    break;
                }
                ans[q.top()-1] = i; 
                q.pop();
            }
        }
        if(flag) {
            for(int i=1; i<=n; i++)
                cout<<ans[i]<<' ';
        }
        else
            cout<<"-1";
        cout<<endl;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

重生之我是oi高手

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值