POJ-1674 Sorting by Swapping 置换群
题目链接:http://poj.org/problem?id=1674
看到题目就想到:ans=n-循环节个数。
1 //STATUS:C++_AC_32MS_212KB 2 #include<stdio.h> 3 #include<stdlib.h> 4 #include<string.h> 5 #include<math.h> 6 #include<iostream> 7 #include<string> 8 #include<algorithm> 9 #include<vector> 10 #include<queue> 11 #include<stack> 12 #include<map> 13 using namespace std; 14 #define LL __int64 15 #define pii pair<int,int> 16 #define Max(a,b) ((a)>(b)?(a):(b)) 17 #define Min(a,b) ((a)<(b)?(a):(b)) 18 #define mem(a,b) memset(a,b,sizeof(a)) 19 #define lson l,mid,rt<<1 20 #define rson mid+1,r,rt<<1|1 21 const int N=10010,INF=0x3f3f3f3f,MOD=40001,STA=8000010; 22 const double DNF=1e13; 23 24 int num[N],vis[N]; 25 int T,n; 26 27 int main() 28 { 29 // freopen("in.txt","r",stdin); 30 int i,j,cnt,u; 31 scanf("%d",&T); 32 while(T--) 33 { 34 cnt=0; 35 mem(vis,0); 36 scanf("%d",&n); 37 for(i=1;i<=n;i++) 38 scanf("%d",&num[i]); 39 40 for(i=1;i<=n;i++){ 41 if(!vis[i]){ 42 cnt++; 43 u=i; 44 while(!vis[u]){ 45 vis[u]=1; 46 u=num[u]; 47 } 48 } 49 } 50 51 printf("%d\n",n-cnt); 52 } 53 return 0; 54 }