POJ Cow Sorting 置換

來源:互聯網
上載者:User

題意:每隻牛都有一個脾氣值,即所謂“牛脾氣”。Farmer John's想把他的N頭牛排序,按脾氣升。他每次可以交換任意兩頭牛,由於脾氣越大越麻煩,每次交換的麻煩程度就是兩頭牛的脾氣之和。求出排好序的最小麻煩程度。

題解:劉汝佳黃亮書,P247-248。

先確定置換。

每個k階置換都可以化成k個對換之積。

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;#define MAXN 100009bool f[MAXN];int num[MAXN], tmp[MAXN], p[MAXN];__int64 solve ( int n ){    __int64 ret = 0;    int tmin, tsum, cnt, ptr;    for ( int i = 1; i <= n; i++ )    {        if ( f[tmp[i]] || tmp[i] == p[tmp[i]] ) continue;        ptr = tmp[i], tsum = cnt = 0, tmin = MAXN;        while ( f[ptr] == 0 )        {            tsum += ptr;            cnt += 1;            if ( ptr < tmin ) tmin = ptr;            f[ptr] = 1;            ptr = p[ptr];        }        ret += min(tsum+cnt*tmp[1]+tmin+tmp[1], tsum+(cnt-2)*tmin);    }    return ret;}int main(){    int n, i;    __int64 ret = 0;    scanf("%d",&n);    for ( i = 1; i <= n; i++ )    {        scanf("%d",&num[i]);        tmp[i] = num[i];    }    sort(tmp+1,tmp+1+n);    memset(f,0,sizeof(f));    for ( i = 1; i <= n; i++ )        p[num[i]] = tmp[i];    ret = solve ( n );    printf("%I64d\n",ret);}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.