1375 D. Replace by MEX
题目大意:
给你一个数列的 mex 的定义:
mex = 不存在于该数列中的最小非负数
然后进行操作:用这个数列的 mex 替换掉该数列中任何元素
最后让输出 操作数 和 每次被替换的序列下标(下标从 1 开始)
题目要求:操作数 < 2n
题目给出:长度为 n 的初始数列
思路分析:
这里想法有些偷鸡,我感觉没有 YES 和 NO 的情况下,基本上操作数都能符合题目要求QWQ(后面才知道,替换一个 a[i] = i ,最多需要两次操作)
所以我的做法就是:求出数列的 mex 然后分情况,如果 mex < n,就进行替换 a[mex] = mex,以达到 a[i] = i(这样数列肯定满足非递减)如果 mex >= n,就替换掉该数列最后一个元素(依然是为了保证数列非递减)
AC代码:
#include <iostream>
#include <cstring>
using namespace std;
const int N = 1010;
const int M = 2020;
int a[N];
int b[N];
int n;
int c[M];
// 求一个数组的 mex
int mex() {
memset(b, 0, sizeof(b));
for (int i = 0; i < n; i++)
b[a[i]]++;
for (int i = 0; i <= n; i++)
if (b[i] == 0)
return i;
}
// 查看是否符合题意(数列非递减)
bool check() {
for (int i = 0; i < n - 1; i++)
if (a[i] > a[i + 1])
return false;
return true;
}
int main() {
int t;
cin >> t;
while (t--) {
cin >> n;
int tol = 0;
for (int i = 0; i < n; i++)
cin >> a[i];
while (1) {
int m = mex();
if (m < n) {
a[m] = m;
c[tol++] = m;
} else {
for (int i = 0; i < n; i++)
if(a[i] != i) {
a[i] = m;
c[tol++] = i;
break;
}
}
if (check())
break;
}
cout << tol << endl;
for (int i = 0; i < tol; i++)
cout << c[i] + 1 << ' ';
cout << endl;
}
return 0;
}