题解 1375D Replace by MEX(思维)

题目链接

  • 将原序列变为 0 0 0 n − 1 n-1 n1的全排列
    例子:
2 2 3
MEX(2,2,3)=0
0 2 3
MEX(0,2,3)=1
0 2 1
MEX(0,2,1)=3
  • 从后往前,按照如下方法交换(ps:绝不是因为语言表达能力不好
example 1:
0 2 1
i == 3, a[i] != i
i == 3, loc == 1
0 2 3
i == 3, loc == 0
1 2 3
loc == 0 结束当前交换
i = 2, a[i] == i
i = 1, a[i] == i

example 2:
2 1 0
i == 3, a[i] != i
i == 3, loc == 0
2 1 3
loc == 0结束当前交换
i == 2, a[i] != i
i == 2, loc == 1
2 0 3
i == 2, loc == 2
1 0 3
i == 2, loc == 0
1 2 3
loc == 0结束当前交换
...

ps:特判i==n的情况

if (i == n) a[i] = i;
else a[i] = 0;

AC代码:

// Test1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <set>
using namespace std;
const int maxn = 1010;
int n, cnt, T;
int a[maxn], ans[maxn << 1], num[maxn], vis[maxn];
int main() {
	cin >> T;
	while (T--) {
		cnt = 0;
		cin >> n;
		for (int i = 1; i <= n; i++) {
			cin >> a[i];
			num[a[i]]++;//记录出现次数
			vis[a[i]] = 1;//记录是否出现
		}
		for (int i = 1, j; i <= n; i++) {
			if (num[a[i]] == 1 && a[i] < n) continue;//只有一个且小于n就不动
			num[a[i]]--;//当前个数减一
			if (num[a[i]] == 0) vis[a[i]] = 0;//如果为0,则标记为没出现过
			for (j = 0; j < n; j++)
				if (!vis[j])
					break;//找到MEX就跳出
			a[i] = j, vis[j] = 1, num[j]++;
			ans[++cnt] = i;//统计答案
		}//第一步
		for (int i = n; i >= 1; i--) {
			if (a[i] == i) continue;
			int loc = a[i], tmp;
			if (i == n) a[i] = i;//特判
			else a[i] = 0;
			ans[++cnt] = i;
			while (loc) {//交换
				tmp = loc;
				loc = a[tmp], a[tmp] = tmp, ans[++cnt] = tmp;//交换
			}
		}//第二步
		cout << cnt << endl;
		for (int i = 1; i <= cnt; i++)
			cout << ans[i] << " ";
		cout << endl;
		for (int i = 0; i <= n; i++)//替下一次初始化
			num[i] = vis[i] = 0;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值