返回题解分享
讨论 / 题解分享/ 帖子详情

交换瓶子(编程题) - 题解

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'

const int N = 1e4 + 10;

int n;
int a[N];
int cnt = 0;

void solve()
{
	cin >> n;
	for (int i = 1; i <= n; i++) cin >> a[i];

	for (int i = 1; i <= n; i++)
	{
		if (a[i] != i) // 如果瓶子不在顺序上 
			cnt++;
		for (int j = i + 1; j <= n; j++) // 找到该瓶子应该在的位置 
			if (a[j] == i)
				swap(a[i], a[j]); // 交换瓶子 
	}

	cout << cnt << endl;
}

signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);

	solve();

	return 0;
}
0 回复 0 转发 0 喜欢 0 阅读
回复 (0)
默认 最新
暂无回复,快来抢沙发!