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

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

Time Limit: 5 Sec  Memory Limit: 64 MB Submit: 712  Solved: 416 [Submit][Status][Discuss]

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).

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
char buf[10000000], *ptr = buf - 1;
int n = 0;
char ch = *++ptr;
while(ch < '0' || ch > '9') ch = *++ptr;
while(ch <= '9' && ch >= '0'){
n = (n << 1) + (n << 3) + ch - '0';
ch = *++ptr;
}
return n;
}
typedef long long ll;
const int maxn = 10000 + 10;
int num[maxn], pos[maxn], a[maxn];
bool vis[maxn] = {false};
int main(){
for(int i = 1; i <= N; i++) num[i] = a[i] = readint();
sort(a + 1, a + N + 1);
for(int i = 1; i <= N; i++) pos[i] = lower_bound(a + 1, a + N + 1, num[i]) - a;
ll ans = 0;
for(int j, Min, tot, siz, i = 1; i <= N; i++){
if(vis[i]) continue;
Min = tot = num[i];
siz = 1;
vis[i] = true;
j = pos[i];
while(!vis[j]){
Min = min(Min, num[j]);
tot += num[j];
siz++;
vis[j] = true;
j = pos[j];
}
ans += min((ll)Min * (siz - 2), (ll)a[1] * (siz + 1) + Min) + tot;
}
printf("%lld\n", ans);
return 0;
}

posted @ 2017-09-19 18:16  Elder_Giang  阅读(177)  评论(0编辑  收藏  举报