Cod sursa(job #1327824)

Utilizator assa98Andrei Stanciu assa98 Data 27 ianuarie 2015 10:09:23
Problema Barman Scor 10
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.2 kb
#include <fstream>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;

ifstream fin("barman.in");
ofstream fout("barman.out");

const int MAX_N = 610;
const int INF = (1 << 30);

int a[MAX_N];
bool viz[MAX_N];
int b[2 * MAX_N];

int solve(int poz, int n) {
    memset(viz, 0, sizeof(viz));
    int ans = 0;
    for(int i = 1; i <= n; i++) {
        if(a[i] == b[poz + i - 1]) {
            viz[i] = true;
        }
    }

    for(int i = 1; i <= n; i++) {
        if(a[i] != b[poz + i - 1]) {
            int p = INF;
            for(int j = 1; j <= n; j++) {
                if(!viz[j] && a[i] == b[j + poz - 1]) {
                    if(abs(i - j) < abs(i - p)) {
                        p = j;
                    }
                }
            }
            ans += 20 + abs(i - poz);
            viz[poz] = true;
        }
    }
    return ans;
}

int main() {
    int n;
    fin >> n;
    for(int i = 1; i <= n; i++) {
        fin >> a[i];
        b[i] = a[i];
    }

    sort(b + 1, b + n + 1);
    for(int i = 1; i <= n; i++) {
        b[n + i] = b[i];
    }

    int ans = INF;
    for(int i = 1; i <= n; i++) {
        ans = min(ans, solve(i, n));
    }

    fout << ans;

    return 0;
}