poj3270 Cow Sorting

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int a[10008];//置换前的序列
int b[10008];//置换后的序列
bool flag[10008];
struct T
{
    int first;//每个循环的起始位置
    int length;//每个循环的长度
    int min;//每个循环的最小值
    int sum;//每个循环的总和
};
int hash[100008];
int data[10008];
T point[10008];
int cmp(const void *a,const void *b)
{
    return (*(int *)a)-(*(int *)b);
}
int main()
{
    int n;
    scanf("%d",&n);
    memset(hash,-1,sizeof(hash));
    int i,j;
    int small=-1;
    for(i=0;i<n;i++)
    {
        scanf("%d",&b[i]);
        a[i]=b[i];
        hash[a[i]]=i;
        if(small==-1||small>b[i])
        {
            small=b[i];
        }
        flag[i]=false;
    }
    qsort(b,n,sizeof(b[0]),cmp);
    int k=0;//循环的个数
    int num=0;//数字的个数
    for(i=0;i<n;i++)
    {
        if(flag[i])
        {
            continue;
        }
        point[k].first=num;
        point[k].length=1;
        point[k].min=a[i];
        point[k].sum=a[i];
        data[num++]=a[i];
        flag[i]=true;
        int temp=a[i];
        while(b[hash[temp]]!=a[i])
        {
            temp=b[hash[temp]];
            data[num++]=temp;
            flag[hash[temp]]=true;
            point[k].length++;
            if(point[k].min>temp)
            {
                point[k].min=temp;
            }
            point[k].sum+=temp;
        }
        k++;
    }
    int temp1,temp2;
    int res;
    int out=0;
    for(i=0;i<k;i++)
    {
        temp1=point[i].sum+(point[i].length-2)*point[i].min;
        temp2=point[i].sum+point[i].min+(point[i].length+1)*small;
        res=(temp1<temp2?temp1:temp2);
        out+=res;
    }
    printf("%d\n",out);
    return 0;
}

posted @ 2012-07-12 08:55  willzhang  阅读(117)  评论(0编辑  收藏  举报