poj 3270 Cow Sorting(置換群)

來源:互聯網
上載者:User

連結:http://poj.org/problem?id=3270

做這道題,是昨天的比賽被1003給虐爆了.

/*Problem ID: poj 3270meaning: 給出一列數,要將其排列成升序序列所需的最少花費,ps:cost 是交換的兩數之和.Analyzing:置換群.黑書p248.找到每個迴圈節的長度ki和它的最小元素ti cost=sum+sum(min(ki-2)*ti,ti+(ki+1)m)*/#include <iostream>#include<algorithm>#include<cstdio>#include<cstdlib>#include<cstring>#include<vector>using namespace std;typedef struct even{int y1,y2,x;}even;#define FOR(i,s,t) for(int i=(s); i<(t); i++)#define LL long long#define BUG puts("here!!!")#define STOP system("pause")#define file_r(x) freopen(x, "r", stdin)#define file_w(x) freopen(x, "w", stdout)#define lson l,m,rt<<1#define rson m+1,r,rt<<1|1#define maxn 10005#define maxm 100005LL gcd(LL a,LL b) {return a?gcd(b%a,a):b;}int main(){    int N,m=maxm;    int A[maxn],B[maxn],hash[maxm],vis[maxn];    scanf("%d",&N);    int cost=0;    FOR(i,0,N){        scanf("%d",&A[i]);        B[i]=A[i];        m=min(m,A[i]);    }    sort(B,B+N);    FOR(i,0,N) hash[B[i]]=i;    memset(vis,0,sizeof(vis));    cost=0;    FOR(i,0,N){    if(!vis[i]){        int ki=0,sum=0;        int temp=A[i],j=i,ti=maxm;        while(1){            vis[j]=1;            ki++;            ti=min(ti,temp);            sum+=temp;            j=hash[temp];            temp=A[j];            if(temp==A[i]) break;        }        cost+=sum+min((ki-2)*ti,ti+(ki+1)*m);    }    }    printf("%d\n",cost);    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.