poj 1674 Sorting by Swapping 置换群

 若置换循环因子阶数分别为 ( a1, a2, ..., ak ) , 则最少交换次数为 (a1-1)+(a2-1)+...+(ak-1) 

解题代码

View Code
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

const int N = 10010;

int a[N], n;
bool vis[N];

int check( int s )
{
    for(int i = s; i <= n; i++)
        if( !vis[i] ) return i;
    return -1;
}
int main()
{
    int T;
    scanf("%d", &T);
    while( T-- )
    {
        scanf("%d", &n);    
        for(int i = 1; i <= n; i++)
            scanf("%d", &a[i] );
        int res = 0, pos = 1;
        memset( vis, 0, sizeof(vis));
        while( (pos=check(pos)) != -1 )
        {
            int s = pos, cnt = 0;
            while( !vis[s] )
            {
                vis[s] = true;
                cnt++;
                s = a[s];
            }
            res += cnt-1;    
        }
        printf("%d\n", res );    
    }
    return 0;
}
原文地址:https://www.cnblogs.com/yefeng1627/p/2844237.html