hdu Cow Sorting 数学题(值得思考)

Cow Sorting

Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 16   Accepted Submission(s) : 2
Problem Description

Farmer John's N (1 ≤ N ≤ 10,000) cows are lined up to be milked in the evening. Each cow has a unique "grumpiness" level in the range 1...100,000. Since grumpy cows are more likely to damage FJ's milking equipment, FJ would like to reorder the cows in line so they are lined up in increasing order of grumpiness. During this process, the places of any two cows (not necessarily adjacent) can be interchanged. Since grumpy cows are harder to move, it takes FJ a total of X+Y units of time to exchange two cows whose grumpiness levels are X and Y.

Please help FJ calculate the minimal time required to reorder the cows.

 

 

Input
Line 1: A single integer:  N
Lines 2.. N+1: Each line contains a single integer: line  i+1 describes the grumpiness of cow  i
 

 

Output
Line 1: A single line with the minimal time required to reorder the cows in increasing order of grumpiness.
 

 

Sample Input
3 2 3 1
 

 

Sample Output
7
**************************************************************************************************************************
看了题解,很久才看懂,无非是状态转换的最小代价,先把状态定义为最终状态,再计算最小代价,中间要用到环的,求每一环的最小代价(这一部分稍微难理解点)
**************************************************************************************************************************
 1 #include<iostream>
 2 #include<string>
 3 #include<cstring>
 4 #include<cstdio>
 5 #include<cmath>
 6 #include<queue>
 7 #include<algorithm>
 8 #include<vector>
 9 using namespace std;
10 struct node
11 {
12     int n,v;
13     bool visit;
14 }p[1000001];
15 int Max,Min,Mmin,ans;
16 int n,m,i,j,k,t,g;
17 int num,sum;
18 bool cmp(node a,node b)
19 {
20     return a.v<b.v;
21 }
22 
23 int main()
24 {
25   while(scanf("%d",&n)!=EOF)
26   {
27       for(int i=1;i<=n;i++)
28       {
29           scanf("%d",&p[i].v);
30           p[i].n=i;
31           p[i].visit=0;
32       }
33       sort(p+1,p+n+1,cmp);
34       Min=p[1].v;
35       Max=p[n].v;
36       ans=0;
37       for(int i=1;i<=n;i++)
38       {
39 
40        t=i;
41        num=0;
42        sum=0;
43        Mmin=Max*15;
44        while(p[t].visit==0)
45        {
46           num++;
47           sum+=p[t].v;
48           Mmin=min(Mmin,p[t].v);
49           p[t].visit=1;
50           t=p[t].n;
51        }
52        if(num>0)
53        {
54            int ans1=sum+(num-2)*Mmin;
55            int ans2=sum+Mmin+(num+1)*Min;
56            ans+=min(ans1,ans2);
57        }
58       }
59       printf("%d\n",ans);
60   }
61   return 0;
62 }
View Code

 

转载于:https://www.cnblogs.com/sdau--codeants/p/3521039.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值