# Cod sursa(job #2058907)

Utilizator Data 6 noiembrie 2017 13:46:28 Barman 20 cpp done Arhiva de probleme 1.22 kb
``````#include <bits/stdc++.h>

using namespace std;

int Solve2(vector<int> A, vector<int> B, int mod) {
int n = B.size();
int ans = 1e9;
for (int it = 0; it < n; ++it) {
int now = 0;
for (int i = 0; i < n; ++i) {
int d = abs(B[i] - A[i]);
now += 20 + min(d, mod - d);
}
ans = min(ans, now);
rotate(B.begin(), B.begin() + 1, B.end());
}
return ans;
}

int Solve(vector<int> A, vector<int> B) {
int n = A.size();

map<int, vector<int>> PA, PB;
set<int> vals;

for (int i = 0; i < n; ++i) {
if (A[i] == B[i]) continue;
PA[A[i]].push_back(i);
PB[B[i]].push_back(i);
vals.insert(A[i]);
}

int ans = 0;
for (auto val : vals) {
ans += Solve2(PA[val], PB[val], n);
}
return ans;
}

int main() {
ifstream cin("barman.in");
ofstream cout("barman.out");

int n; cin >> n;
vector<int> A(n), B(n);
for (int i = 0; i < n; ++i) {
cin >> A[i];
B[i] = A[i];
}

int ans = 1e9;
sort(B.begin(), B.end());
for (int it = 0; it < n; ++it) {
ans = min(ans, Solve(A, B));
rotate(B.begin(), B.begin() + 1, B.end());
}
cout << ans << endl;
}
``````