The puzzle

The puzzle:

传送门:http://acm.hdu.edu.cn/showproblem.php?pid=6489

找大佬讲了一下这道题,但还是不懂为什么要这样做,先记录一下以后再研究研究;

解题思路:

 这道题是把序列换几次能到增序列,一上来pos数组记录一下每个数都在什么位置,然后就从1开始和第一个数进行匹配(数列是1-n的),如果不相等,那我们只要进行一次交换就可以把i放到这个位置,之前记录了每个数的位置直接进行更改i与pos[i]的位置就可以 然后ans++ 
 
(如果有看到的大佬,欢迎留言教教我QAQ)
 
 
AC代码如下:
 1 /* */
 2 # include <bits/stdc++.h>
 3 
 4 using namespace std;
 5 const int N=1e5 + 10;
 6 int pos[N];
 7 
 8 int main()
 9 {
10     int t;
11     scanf("%d", &t);
12     while( t-- )
13     {
14         int n;
15         scanf("%d", &n);
16         for( int i=1; i<=n; i++ )
17         {
18             int x;
19             scanf("%d", &x);
20             pos[x] = i;
21         }
22 
23         int ans = 0;
24 
25         for( int i=1; i<=n; i++ )
26         {
27             while( pos[i]!=i )
28             {
29                 swap(pos[i], pos[pos[i]] );
30                 ans++;
31             }
32         }
33         printf("%d\n", ans);
34     }
35     return 0;
36 }
View Code
 

猜你喜欢

转载自www.cnblogs.com/wsy107316/p/10894362.html