http://poj.org/problem?id=3270
这道题就是给你一个无序序列转换成有序序列需要花费的代价最小,交换a和b代价为a+b;
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #define maxn 20000 5 using namespace std; 6 7 int min1=100000; 8 int n; 9 bool vis[maxn]; 10 struct node 11 { 12 int num; 13 int id; 14 bool operator <(const node &a)const 15 { 16 return num<a.num; 17 } 18 }p[maxn*2]; 19 20 int deal() 21 { 22 int ans=0; 23 for(int i=0; i<n; i++) 24 { 25 if(!vis[i]) 26 { 27 vis[i]=true; 28 int sum=p[i].num; 29 int m1=p[i].num; 30 int t1=1; 31 int id=p[i].id; 32 while(id!=i) 33 { 34 vis[id]=true; 35 sum+=p[id].num; 36 m1=min(m1,p[id].num); 37 id=p[id].id; 38 t1++; 39 } 40 ans+=min(sum+(t1-2)*m1,sum+m1+(t1+1)*min1); 41 } 42 } 43 return ans; 44 } 45 46 int main() 47 { 48 while(scanf("%d",&n)!=EOF) 49 { 50 memset(vis,false,sizeof(vis)); 51 for(int i=0; i<n; i++) 52 { 53 scanf("%d",&p[i].num); 54 p[i].id=i; 55 min1=min(min1,p[i].num); 56 } 57 sort(p,p+n); 58 printf("%d\n",deal()); 59 } 60 return 0; 61 }
poj 3270 Cow Sorting,布布扣,bubuko.com
原文地址:http://www.cnblogs.com/fanminghui/p/3759837.html