poj 3270 Cow Sorting

题意:有一串数字,要将它排列成升序,每次可以交换两个数,交换一次的代价为两数之和。要求代价最小。

思路:读完题,没有思路,知道是关于polya的,但是也只会最简单的求有多少种染色方法,然后上网搜题解,再然后参考大神的题解,终于明白了,还是要继续学习polya啊,

大神的博客:http://www.cnblogs.com/mcflurry/archive/2012/06/21/2557798.html

代码:

View Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <queue>
#define  N 10004
#define  INF 1000000
using namespace std ;

int num[N] , pos[N*10] , vis[N] ;
int minx , maxx , n ;

int find ()
{
    int i , len , x , sum , t_min ;
    int ss = 0 ;
    
    //计数排序求循环节的长度
    memset( vis , 0 , sizeof ( vis )) ;
    for ( i = 1 ; i <= n ; i++ )
    {
        len = 0 ;
        x = i ;
        sum = 0 ;
        t_min = INF ;
        while ( !vis[x] )
        {
            vis[x] = 1 ;
            len++ ;
            sum += num[x] ;
            if ( num[x] < t_min )
            t_min = num[x] ;
            x = pos[num[x]] ;
        }
        if ( len > 0 )
        {
            int s1 = sum + ( len - 2 ) * t_min ;
            int s2 = sum + t_min + ( len + 1 ) * minx ;
            ss += s1 < s2 ? s1 : s2 ;
        }
    }
    return ss ;
}

int main()
{
    int i , j ;

    while ( scanf ( "%d" , &n ) != EOF )
    {
        for ( i = 1 ; i <= n ; i++ )
        scanf ( "%d" , &num[i] );

        memset( pos , 0 , sizeof ( pos )) ;
        minx = INF ; maxx = -INF ;
        for ( i = 1 ; i <= n ; i++ )
        {
            pos[num[i]] = 1 ;
            if ( num[i] > maxx )
            maxx = num[i] ;
            if ( num[i] < minx )
            minx = num[i] ;
        }
        for ( i = 1 ; i <= maxx ;  i++ )
        pos[i] += pos[i-1] ;

        printf ( "%d\n" , find () );
    }
    return 0 ;
}
posted @ 2012-08-18 20:19  Misty_1  阅读(173)  评论(0编辑  收藏  举报