题解分享
题解分享简介
交换瓶子(编程题) - 题解
```
#include <bits/stdc++.h>
typedef long long LL;
using namespace std;
const int N=10010;
int n,w,m;
int a[N];
int main()
{
cin>>n;
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
int sum=0;
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[j],a[i]);
}
sum++;
}
}
cout<<sum<<endl;
return 0;
}
```
查看全文
0
0
0
3
交换瓶子(编程题) - 题解
```cpp
#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
1
交换瓶子(编程题) - 题解
```
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
const int N=100010;
int n;
int a[N];
int 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<<endl;
return 0;
}
```
查看全文
0
0
0
1



