# BZOJ1697: [Usaco2007 Feb]Cow Sorting牛排序

## 1697: [Usaco2007 Feb]Cow Sorting牛排序

Time Limit: 5 Sec  Memory Limit: 64 MB
Submit: 387  Solved: 215
[Submit][Status]

3
2
3
1

## Sample Output

7

2 3 1 : 初始序列
2 1 3 : 交换脾气为3和1的牛(时间=1+3=4).
1 2 3 : 交换脾气为1和2的牛(时间=2+1=3).

## Source

 1 #include<cstdio>
2 #include<cstdlib>
3 #include<cmath>
4 #include<cstring>
5 #include<algorithm>
6 #include<iostream>
7 #include<vector>
8 #include<map>
9 #include<set>
10 #include<queue>
11 #include<string>
12 #define inf 1000000000
13 #define maxn 15000
14 #define maxm 500+100
15 #define eps 1e-10
16 #define ll long long
17 #define pa pair<int,int>
18 #define for0(i,n) for(int i=0;i<=(n);i++)
19 #define for1(i,n) for(int i=1;i<=(n);i++)
20 #define for2(i,x,y) for(int i=(x);i<=(y);i++)
21 using namespace std;
23 {
24     int x=0,f=1;char ch=getchar();
25     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
26     while(ch>='0'&&ch<='9'){x=10*x+ch-'0';ch=getchar();}
27     return x*f;
28 }
29 ll n,mi,cs=0,a[maxn],b[maxn],c[maxn];
30 bool check[maxn];
31 inline bool cmp(int x,int y)
32 {
33     return a[x]<a[y];
34 }
35 int main()
36 {
37     freopen("input.txt","r",stdin);
38     freopen("output.txt","w",stdout);
41     sort(b+1,b+n+1,cmp);
42     for1(i,n)c[b[i]]=i;
43     ll ans=0;
44     mi=a[b[1]];
45     for1(i,n)
46      if(!check[i])
47       {
48           ll j=i,len=0,tmp=inf,sum=0;
49           while(!check[j])
50           {
51            check[j]=1;
52            tmp=min(tmp,a[j]);
53            sum+=a[j];
54            len++;
55            j=c[j];
56           }
57         ans+=sum+min((len-2)*tmp,mi*(len+1)+tmp);
58       }
59     cout<<ans<<endl;
60     return 0;
61 }
View Code

posted @ 2014-09-07 20:00  ZYF-ZYF  Views(161)  Comments(0Edit  收藏  举报