Codeforces Global Round 9 D. Replace by MEX题解(构造)

题目链接

题目大意

给你一个有n个元素的数组a(n<=1000),最多进行2*n次操作,使得这个数组为非严格单调上升数组。

操作定义为任意选定一个元素,使其变成mex。

mex的定义:The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array.

题目思路

写了一个多小时都不会写。。。一直以为是有一个通解

其实就是构造成0,1,2…n-1

标准题解

在这里插入图片描述

代码

#include<map>
#include<cstdio>
#include<cmath>
#include<vector>
#include<cstring>
#include<algorithm>
#define debug printf("I am here\n");
using namespace std;
typedef long long ll;
const int maxn=1000+5,inf=0x3f3f3f3f,mod=1e9+7;
int t,n,m,a[maxn];
bool used[maxn];
int cal(){//找到mex
    memset(used,0,sizeof(used));
    for(int i=1;i<=n;i++){
        used[a[i]]=1;
    }
    for(int i=0;i<=n;i++){
        if(!used[i]){
            return i;
        }
    }
}
bool check(){//构造 0 1 2 3 .... n-1
    for(int i=1;i<=n;i++){
        if(a[i]!=i-1){
            return 0;
        }
    }
    return 1;
}
int main(){
    scanf("%d",&t);
    while(t--){
        vector<int> vec;
        scanf("%d",&n);
        for(int i=1;i<=n;i++){
            scanf("%d",&a[i]);
        }
        while(1){
            if(check()){//满足条件
                break;
            }
            int mex=cal();
            if(mex==n){//给没有匹配的位置放上n
                for(int i=1;i<=n;i++){
                    if(a[i]!=i-1){
                        a[i]=mex;
                        vec.push_back(i);
                        break;//注意要break
                    }
                }
            }else{
                vec.push_back(mex+1);
                a[mex+1]=mex;
            }
        }
        printf("%d\n",(int)vec.size());
        for(int i=0;i<vec.size();i++){
            printf("%d ",vec[i]);
        }
        printf("\n");
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值