标签:
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 Hint 2 3 1 : Initial order.
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
John的牧场里有n头牛,每头牛有一个等级level,保证没有相同等级的牛。 原来置换还可以这么玩!涨姿势 首先考虑把原始序列变成几个置换。如 除此之外还有一种情况可能更优: 总花费small*(len+1)+sum+min 两种情况取最小即可。 |
代码如下:
#include <iostream>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
#include <list>
#include <algorithm>
#include <map>
#include <set>
#define LL long long
#define Pr pair<int,int>
#define fread() freopen("in.in","r",stdin)
#define fwrite() freopen("out.out","w",stdout)
using namespace std;
const int INF = 0x3f3f3f3f;
const int msz = 10000;
const int mod = 1e9+7;
const double eps = 1e-8;
struct Group
{
int len,mn,sum;
};
struct Moon
{
int level,id;
bool operator <(const struct Moon a)const
{
return level < a.level;
}
};
Moon mn[10010];
Group gp[10010];
int tp;
int num[10010];
int val[10010];
bool vis[10010];
void solve(int pos,int id)
{
gp[tp].mn = INF;
gp[tp].len = gp[tp].sum = 0;
while(!vis[id])
{
vis[id] = 1;
gp[tp].len++;
gp[tp].mn = min(gp[tp].mn,val[id]);
gp[tp].sum += val[id];
id = num[id];
}
}
int main()
{
//fread();
//fwrite();
int n;
scanf("%d",&n);
for(int i = 0; i < n; ++i)
{
scanf("%d",&mn[i].level);
mn[i].id = i;
}
sort(mn,mn+n);
for(int i = 0; i < n; ++i)
{
num[mn[i].id] = i;
val[i] = mn[i].level;
}
tp = 0;
int mn = INF;
memset(vis,0,sizeof(vis));
for(int i = 0; i < n; ++i)
{
if(vis[i]) continue;
solve(tp,i);
mn = min(mn,gp[tp++].mn);
}
int ans = 0;
for(int i = 0; i < tp; ++i)
{
ans += min( gp[i].mn*(gp[i].len-1)+gp[i].sum-gp[i].mn,
mn*(gp[i].len+1)+gp[i].mn+gp[i].sum );
}
printf("%d\n",ans);
return 0;
}
标签:
原文地址:http://blog.csdn.net/challengerrumble/article/details/52229091