蓝桥杯每日一题2023.11.20

题目描述

"蓝桥杯"练习系统 (lanqiao.cn)

题目分析

方法一:暴力枚举,如果说数字不在正确的位置上也就意味着这个数必须要改变,进行改变记录即可

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int n, a[N], ans;
int main()
{
	cin >> n;
	for(int i = 1; i <= n; i ++)cin >> a[i];
	for(int i = 1; i <= n; i ++)
	{
		if(a[i] != i)
		{
			for(int j = i + 1; j <= n; j ++)
			{
				if(a[j] == i)
				{
					swap(a[i], a[j]);
					ans ++;
				}
			}
		}
	}
	cout << ans;
	return 0;
}

方法二:置换群算法,每个数字和对应位置相连可以组成一个环,如果说每个数字可以形成自环也就说明每一个数字都在自己正确的位置上,我们可以找出有几个环,n - 环的个数则为需要交换的个数。

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int a[N], n, cnt;
bool st[N];
int main()
{
	cin >> n;
	for(int i = 1; i <= n; i ++)cin >> a[i];
	for(int i = 1; i <= n; i ++)
	{
		if(!st[i])
		{
			cnt ++;
			for(int j = i; !st[j]; j = a[j])
			{
				st[j] = true;
			}
		}
	}
	cout << n - cnt;
	return 0;
}
相关推荐
ychqsq1 天前
201.春风
经验分享·职场和发展
泡沫_花火1 天前
大模型开发相关岗位面试资料(含算法)
语言模型·自然语言处理·面试·职场和发展
我命由我123451 天前
Photoshop - Photoshop 快速共享作品
学习·ui·职场和发展·求职招聘·职场发展·学习方法·photoshop
我命由我123451 天前
自动化 / 智能装配的对象、内容、层级
运维·学习·职场和发展·自动化·求职招聘·职场发展·学习方法
AI职业加油站1 天前
大模型开发工程师证书怎么考?零基础学习路径与价值拆解
大数据·人工智能·学习·职场和发展·数据分析
blxr_1 天前
力扣hot100爬楼梯https://leetcode.cn/problems/climbing-stairs/
算法·leetcode·职场和发展
我命由我123451 天前
Photoshop - 将Photoshop图像置入其他应用程序
学习·ui·职场和发展·求职招聘·职场发展·学习方法·photoshop
blxr_2 天前
力扣hot100前k个高频元素https://leetcode.cn/problems/top-k-frequent-elements/
算法·leetcode·职场和发展
财情双生教练易和中2 天前
“找矿大会战”产业链,量化统计研究报告
职场和发展·职业发展·创业创新·程序员创富
yuanxi2002 天前
001267拟扩产光模块:大客户销售如何用价值力读一条扩产公告
人工智能·职场和发展·创业创新·学习方法