The minimum cost of sorting (permutation group)

To give you a sequence s = {a1, a2 ...... an}, then any two of the switching element i, j of the position, the expense ai + aj, into the ordered sequence, find the minimum cost

Ideas: ingenious application of permutation groups 

In 4327165 Paint Example

There are three rings

4->7->5->1->4

3->2->3

6->6

It requires the minimum cost, in the ring with the smallest element to move through the other elements

Cost: Σwi + (n-2) * min (wi)

After adding the calculated consideration is the cost of each ring

But there are counter-examples, it may sometimes be less costly by borrowing the outer ring element

The increased cost of borrowing cost: 2 * (min (wi) + x) // x is the smallest element of the whole sequence 

Cost savings are: (n-1) * (min (wi) -x)

At this time total cost: Σwi + (n-2) * min (wi) + 2 * (min (wi) + x) - (n-1) * (min (wi) -x) = Σwi + min (wi) + (n + 1) * x

Summary: seeking the minimum cost should be considered as a whole by the smallest element in both cases and did not hesitate element

#include <iostream>
#include <algorithm>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 100100;
int a[maxn], b[maxn], T[maxn], n, minn;
bool vis[maxn];
int solve() {
    int ans = 0;
  //枚举每个环
for (int i = 0; i < n; i++) { if (vis[i]) continue; int cur = i,sum = 0; int mini = inf; int k = 0 ; while ( 1 ) { k ++ ; you [why] = 1 ; int y = a [why]; sum + = v; Mini = min (mini, v); Why = T [v]; if (you [why]) break ; } Ans + = min (I + (k - 2 ) * mini, mini + I + (k + 1 ) * minn); } return ans; } int main() { cin >> n; minn = inf; for (int i = 0; i < n; i++) { cin >> a[i]; b[i] = a[i]; vis[i] = 0; minn = min(minn, a[i]); } sort(b, b + n); for (int i = 0; i < n; i++) T[b[i]] = i; int ans = solve(); cout << ans << endl; return 0; }

Example: http://poj.org/problem?id=3270

Guess you like

Origin www.cnblogs.com/wronin/p/11352411.html