Cod sursa(job #2504799)

Utilizator mihaicivMihai Vlad mihaiciv Data 5 decembrie 2019 16:35:35
Problema Dezastru Scor 70
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.65 kb
#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

int n, k;
double a[100];
int vis[100], v[100];
double total_sum;
double total_ans;

ifstream f("dezastru.in");
ofstream g("dezastru.out");

bool valid(int x) {
    if (vis[x] == 1) return false;
    return true;
}

void calculare(int tip) {

    if (tip == 1) {
        double current_val = 1;
        for (int i = 1; i <= k; ++i) {
            //cout << v[i] << " ";
            current_val *= a[v[i]];
        }
        total_sum += current_val;
        //cout << "\n";
        total_ans ++;
    } else {
        double current_val = 1;
        for (int i = 1; i <= n; ++i) {
            if (vis[i]) continue;
            //cout << v[i] << " ";
            current_val *= a[i];
        }
        total_sum += current_val;
        //cout << "\n";
        total_ans ++;
    }
}

void bk(int x, double prod, int tip) {

    for (int i = 1; i <= n; ++i) {
        v[x] = i;
        if (valid(i)) {
            vis[i] = 1;
            prod = prod * a[v[x]];
            if (x == k) {
                //total_sum += prod;
                //total_ans ++;
                calculare(tip);
            } else bk(x + 1, prod, tip);
            prod = prod / a[v[x]];
            vis[i] = 0;
        }
    }

}

int main() {

    f >> n >> k;
    for (int i = 1; i <= n; ++i) {
        f >> a[i];
    }

    if (k >= n / 2) {
        k = n - k;
        bk(1, 1, 0);
        g << setprecision(6) << (total_sum / total_ans);
        return 0;
    }

    bk(1, 1, 1);

    g << setprecision(6) << (total_sum / total_ans);

    return 0;
}