POJ 3270 Cow Sorting
来源:互联网 发布:热力学书 推荐 知乎 编辑:程序博客网 时间:2024/05/16 07:06
这道题运用了置换的知识。
题目大意:
用两两交换的方式给一个数列排序,每交换一次的代价是这两个数之和求最小代价。
解题思路:
对于这种情况,我们在数列中找置换环。每个置换环内的数都是可以回归到它应有的位置上并且不影响其他的置换环。
置换环归位的代价有两种,第一种是用环内最小的数与其他数交换,另一种是用整个数列中最小的数与环内最小的数交换,完成环内所有数的归位后在换回去。
下面是代码:
#include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>#include <vector>#include <queue>#include <set>#include <map>#include <string>#include <math.h>#include <stdlib.h>#define clear(A, X, SIZE) memset(A, X, sizeof(A[0]) * (SIZE))#define clearall(A, X) memset(A, X, sizeof(A))#define max( x, y ) ( ((x) > (y)) ? (x) : (y) )#define min( x, y ) ( ((x) < (y)) ? (x) : (y) )using namespace std;struct node{ int num,po1,po2;} x[10005];bool cmp(const node a,const node b){ return a.num<b.num;}bool cmp1(const node a,const node b){ return a.po1<b.po1;}int num[10005],po[10005];bool vis[10005];int main(){ int n,minnum,min2,minp,cost1,cost2,ans,tp; while(scanf("%d",&n)!=EOF) { ans=0; minnum=1<<30; for(int i=0; i<n; i++) { scanf("%d",&num[i]); x[i].num=num[i]; x[i].po1=i; minnum=min(minnum,num[i]); } sort(x,x+n,cmp); for(int i=0; i<n; i++) { x[i].po2=i; po[i]=x[i].po1; } sort(x,x+n,cmp1); clearall(vis,false); int cnt=n,p; bool flat; for(int i=0; i<n&&cnt; i++) { if(!vis[i]) { vis[i]=true; p=x[i].po2; min2=x[i].num; minp=i; while(p!=i) { vis[p]=true; if(min2>x[p].num) { min2=x[p].num; minp=p; } p=x[p].po2; } cost1=0; cost2=0; p=minp; while(p!=x[minp].po2) { cost1+=x[po[p]].num+min2; cost2+=x[po[p]].num+minnum; p=po[p]; } ans+=min(cost1,cost2+2*(min2+minnum)); } } printf("%d\n",ans); } return 0;}
0 0
- poj 3270 Cow Sorting
- POJ 3270(Cow Sorting)
- poj 3270 Cow Sorting
- POJ 3270 Cow Sorting
- POJ 3270 Cow Sorting
- POJ 3270 Cow Sorting
- POJ 3270 Cow Sorting
- POJ 3270 Cow Sorting
- POJ 3270 Cow Sorting
- POJ-3270 Cow Sorting
- POJ 3270 Cow Sorting (置换)
- POJ 3270 / HDU 2838 - Cow Sorting
- POJ 3270 Cow Sorting(置换循环节)
- poj 3270 Cow Sorting(置换群)
- poj-3270-Cow Sorting-置换群
- POJ 3270 Cow Sorting 置换应用
- Cow Sorting && Permutations(poj 3270 && 2369)
- poj 3270 Cow Sorting (置换群)
- 划分树---原理
- tomcat+apache集群
- linux 安装pcre
- LeetCode——Search in Rotated Sorted Array
- BZOJ 1624: [Usaco2008 Open] Clear And Present Danger 寻宝之路
- POJ 3270 Cow Sorting
- HDU-#1560 DNA sequence(迭代加深搜)
- Python入门(四,高级)
- 二叉查找树 红黑树 2-3-4树 定义
- Toast有时候不显示问题的解决
- Java杂谈之二----怎样判断一个数是水仙花数以及穷举水仙花数
- HTML框架
- Linux系统编程(23)——信号的阻塞
- BZOJ 1625: [Usaco2007 Dec]宝石手镯