Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 6750 | Accepted: 2633 |
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
Lines
2..N+1: Each line contains a single integer: line i+1 describes
the grumpiness of cow i.
Output
to reorder the cows in increasing order of grumpiness.
Sample Input
3
2
3
1
Sample Output
7
Hint
2 1 3 : After interchanging
cows with grumpiness 3 and 1 (time=1+3=4).
1 2 3 : After interchanging cows
with grumpiness 1 and 2 (time=2+1=3).
Source
输入
line1行:一个整数:N
line2行:N + 1:每行包含一个整数:line+ 1描述了牛一、暴躁
输出
line 1:一个需要在暴躁的情绪增加的顺序排列的最小时间行牛。
样例解释
3 1 2:初始订单。
2 1 3:交换后奶牛暴躁3和1(时间= 1 + 3 = 4)。
1 2 3:交换后奶牛暴躁1和2(时间= 2 + 1 = 3)。
解析思路
同:给你一列数,需要将这些数按升序排列。你可以每次交换任意两个数的位置,而一次交换的代价被定义成交换的两个数的和。写一程序,用最小代价来完成这项无聊的排序工作。
则 最终的式子就是 ans=sum(整个数列的和)+sigma(min((k-2)*mini,(k+1)*min+mini));
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define N 101000
int a[N],b[N],c[N];
bool d[N];
int n,ans=,mi;
int main(){
//freopen("sh.txt","r",stdin);
mi=0x7f;
scanf("%d",&n);
for(int i=;i<n;i++){
scanf("%d",a+i);
b[i]=a[i];
mi=min(mi,a[i]);
c[a[i]]=i;//记录原来数字的下标
}
sort(b,b+n);//调整成正确的队列便于比较
memset(d,,sizeof(d));
while(n){
int sum=,t=,i=,mmm=0x7f;
while(d[i]) i++;
int beg=i;
do{
t++;
d[i]=;
mmm=min(mmm,a[i]);
sum+=a[i];
i=c[b[i]];
}while(i!=beg);
n-=t;
if(t==)continue;
int v1=(t-)*mmm;
int v2=mmm+(t+)*mi;
ans+=min(v1,v2);//累加最小次数
ans+=sum;
}
printf("%d\n",ans);
return ;
}