Cod sursa(job #2653030)

Utilizator irimia_alexIrimia Alex irimia_alex Data 26 septembrie 2020 18:17:19
Problema Ciclu hamiltonian de cost minim Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

vector<pair<int,int>> *g;
vector<int> h;
vector<bool> viz;
int n, min_cost = 1e9;

void show() {
    for (auto u : h)
        cout << u << ' ';
    cout << '\n';
}

void bt(int u,int cost) {
    viz[u] = true;
    h.push_back(u);
    if (h.size() == n) {
        for (auto v : g[u])
            if (v.first == h[0]) {
                if (cost + v.second < min_cost)
                    min_cost = cost + v.second;
                break;
            }
    }
    else {
        for (auto v : g[u])
            if (!viz[v.first])
                bt(v.first, cost + v.second);
    }
    h.pop_back();
    viz[u] = false;
}

int main() {
    
    ifstream fin("hamilton.in");
    ofstream fout("hamilton.out");

    int m;
    fin >> n >> m;
    g = new vector<pair<int,int>>[n + 1];
    viz.resize(n + 1, false);
    while (m--) {
        int x, y, z;
        fin >> x >> y >> z;
        g[x].push_back({ y,z });
    }

    bt(0, 0);
    if (min_cost != 1e9)
        fout << min_cost;
    else fout << "Nu exista solutie";

    delete[] g;

    return 0;
}