题目描述
Kayaking is playing a puzzle game containing n different blocks. He marks the blocks with integers from 1 to n, which show the blocks’ original positions. Each time he can exchange two blocks and he wants to know how many times he needs at least to restore the puzzle.
输入
The input starts with one line contains exactly one positive integer T which is the number of test cases.
Each test case contains two lines.
The first line contains an integer, which indicates the number of puzzle pieces.
The second line contains n different integers, the i-th number means the mark of the block in the i-th position.
输出
For each test case, output one line with one number represents the minimum operations.
样例输入
2
4
2 3 4 1
4
2 1 4 3
样例输出
3
2
题目大意:
从1到n一共n个数,排序,每次操作就是把两个数倒个个,求最少操作次数,使得排序为从1到n。
代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
int a[100010];
int vis[100010]={0};
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
int res=0;
for(int i=1;i<=n;i++)
{
int tmp=a[i],count=0;
while(!vis[tmp])
{
vis[tmp]=1;
tmp=a[tmp];
cnt++;
}
if(count>0)
res+=(count-1);
}
printf("%d\n",res);
}
return 0;
}
博客围绕一个数字排序问题展开,给定从1到n的n个数,每次可交换两个数的位置,要求找出最少操作次数使数字按顺序排列。文中给出了题目描述、输入输出要求及样例,还提及了代码但未展示。
292

被折叠的 条评论
为什么被折叠?



