Cod sursa(job #2418240)

Utilizator SemetgTemes George Semetg Data 4 mai 2019 14:14:10
Problema Oo Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.13 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
using namespace std;

const string FILE_NAME = "oo";
const int N_MAX { 100005 };
using Node = pair< int, pair<int, int> >;

ifstream in { FILE_NAME + ".in" };
ofstream out { FILE_NAME + ".out" };

int N;
priority_queue< Node, vector<Node>, less<Node> > q;
vector<char> a(N_MAX);
int sol;

void init() {
    in >> N;
    
    for (int i { 1 }; i <= N; ++i) {
        int x;
        in >> x;
        a[i] = x;
    }
    
    q.push({ a[1] + a[N], { 1, N } });
    for (int i { 1 }; i < N; ++i)
        q.push({ a[i] + a[i + 1], { i, i + 1 } });
}

void solve() {
    while (!q.empty()) {
        int val { q.top().first }, x { q.top().second.first }, y { q.top().second.second };
        q.pop();
        if (a[x] == -1 || a[y] == -1)
            continue;
        
        sol += val;
        a[x] = a[y] = -1;
        if (x != 1)
            a[x - 1] = -1;
        else
            a[N] = -1;
        
        if (y != N)
            a[y + 1] = -1;
        else
            a[1] = -1;
    }
}

void print() {
    out << sol;
}

int main() {
    init();
    solve();
    print();
}