POJ Cow Sorting 置换

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define MAXN 100009
bool f[MAXN];
int num[MAXN], tmp[MAXN], p[MAXN];

__int64 solve ( int n )
{
__int64 ret = 0;
int tmin, tsum, cnt, ptr;
for ( int i = 1; i <= n; i++ )
{
if ( f[tmp[i]] || tmp[i] == p[tmp[i]] ) continue;
ptr = tmp[i], tsum = cnt = 0, tmin = MAXN;
while ( f[ptr] == 0 )
{
tsum += ptr;
cnt += 1;
if ( ptr < tmin ) tmin = ptr;
f[ptr] = 1;
ptr = p[ptr];
}
ret += min(tsum+cnt*tmp[1]+tmin+tmp[1], tsum+(cnt-2)*tmin);
}
return ret;
}

int main()
{
int n, i;
__int64 ret = 0;
scanf("%d",&n);
for ( i = 1; i <= n; i++ )
{
scanf("%d",&num[i]);
tmp[i] = num[i];
}
sort(tmp+1,tmp+1+n);
memset(f,0,sizeof(f));
for ( i = 1; i <= n; i++ )
p[num[i]] = tmp[i];
ret = solve ( n );
printf("%I64d\n",ret);
}


hdu 2838 Cow Sorting（树状数组）

2014-07-23 18:48:50

3270 Cow Sorting //利用置换排序

2011-02-13 13:28:00

Cow Sorting POJ - 3270 （置换）

2017-07-28 20:32:39

poj 3270 Cow Sorting（置换）

2016-05-20 20:14:00

POJ 3270 Cow Sorting（置换）

2017-08-04 20:25:57

POJ 3270 Cow Sorting（置换）

2017-10-02 22:55:36

POJ 3270 Cow Sorting (置换)

2017-04-25 16:43:44

POJ - 3270 Cow Sorting 置换

2017-08-30 22:20:00

POJ 3278 Catch That Cow（BFS）

2014-01-13 19:24:25

POJ-1007:DNA Sorting

2012-01-17 22:48:35