POJ 3270 (Cow Sorting)

Source: Internet
Author: User

This is mainly because the minimum price is required during the exchange.
First, find the same number in the ring and connect it to the same column.
1. First behavior Starting sequence 2 behavior target sequence

Swap the smallest vertex in a ring with the number of points

 

Last Switch 3 2

 

Or the smallest number in the sequence and the smallest number in the ring (Boat problem ?)


In this way, the optimal solution is obtained.

Ans + = min (sizi-2) * mini + sumi,
(Sizi + 1) * minn + mini + sumi


[Cpp]
# Include <cstdio>
# Include <cmath>
# Include <iostream>
# Include <cstdlib>
# Include <cstring>
# Include <functional>
# Include <algorithm>
Using namespace std;
# Define MAXN (10000 + 10)
# Define MAXAI (100000 + 10)
Int n, a [MAXN], a2 [MAXN], hpos [MAXAI], ans = 0;
Bool B [MAXN];
 
Int main ()
{
// Freopen ("cowsorting. in", "r", stdin );
Scanf ("% d", & n );
For (int I = 1; I <= n; I ++) scanf ("% d", & a [I]);
Memcpy (a2, a, sizeof ());
Sort (a2 + 1, a2 + 1 + n, less <int> ());
Int minn = a2 [1];
Memset (B, false, sizeof (B ));
For (int I = 1; I <= n; I ++)
Hpos [a [I] = I;


For (int I = 1; I <= n; I ++)
{
// Cout <a2 [I] <''<a [I] <endl;
If (! B [I] & a2 [I]! = A [I])
{
B [I] = 1;
Int mini = a [I], start = I, sizi = 1, sumi = a [I];
Int now = hpos [a2 [I];
While (now! = Start)
{
B [now] = 1;
Sizi ++;
Sumi + = a [now];
Mini = min (mini, a [now]);
Now = hpos [a2 [now];
}
Ans + = min (sizi-2) * mini + sumi, (sizi + 1) * minn + mini + sumi );

}
}





/// 000
// For (int I = 1; I <= n; I ++) printf ("% d", a2 [I]);
/// 000
Printf ("% d \ n", ans );

// While (1 );
Return 0;
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.