Cod sursa(job #2505058)

Utilizator mihaicivMihai Vlad mihaiciv Data 6 decembrie 2019 08:56:13
Problema Dezastru Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.08 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;
double total_prod;

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 = v[x - 1] + 1; i <= n; ++i) {
        v[x] = i;
        if (valid(i)) {
            vis[i] = 1;
            prod = prod * a[v[x]];
            total_prod = total_prod / a[v[x]];
            if (x == k) {
                if (tip == 1) {
                    total_sum += prod;
                    total_ans ++;
                } else {
                    total_sum += total_prod;
                    total_ans ++;
                }
            } else if (k - x <= n - i) {
                bk(x + 1, prod, tip);

            }
            prod = prod / a[v[x]];
            total_prod = total_prod * a[v[x]];
            vis[i] = 0;
        }
    }

}

int main() {

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

    if (k == n) {
        g << total_prod;
        return 0;
    }

    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;
}