Cod sursa(job #2941097)

Utilizator TeodoraMaria123Serban Teodora Maria TeodoraMaria123 Data 17 noiembrie 2022 09:46:57
Problema Ciclu hamiltonian de cost minim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2 kb
#include <fstream>
#include <vector>
#include <bitset>

using namespace std;

ifstream in("hamilton.in");
ofstream out("hamilton.out");

#define MAX_VERTICES 18
#define MAX_COST 1000000
#define MAX_STATE 530000
#define MAX_EDGES 400

int n, m, minimCost = MAX_COST * MAX_EDGES, foundCycle;
vector <vector <pair <int,int> > > graph;
int dp[MAX_VERTICES][MAX_STATE + 1];
bool dpp[MAX_VERTICES][MAX_STATE + 1];

void readGraph() {
    in >> n >> m;
    graph.resize(n + 1);
    for(int i = 1; i <= m; i ++) {
        int a, b, c;
        in >> a >> b >> c;
        graph[a].push_back({b, c});
    }
}

void printDpp() {
    int stateNo = (1 << n) - 1;
    for(int mask = 1; mask <= stateNo; mask ++) {
        for(int i = 0; i < n; i++) {
            out << dpp[i][mask] << " ";
        }
        out << "\n";
    }
}

void hamilton() {
    int startingNode = 0, initialMask, stateNo;

    stateNo = (1 << n) - 1;
    initialMask = 1 << startingNode;
    dp[startingNode][startingNode] = 0;
    dpp[startingNode][initialMask] = 1;

//    printDpp();
    for(int mask = initialMask; mask <= stateNo; mask ++)
        for(int i = 0; i < n; i ++) {
            if(mask & (1 << i))
                for(auto x : graph[i]) {
                    if((mask & (1 << x.first))  &&  dpp[i][mask - (1 << x.first)]) {
                        dpp[x.first][mask] = 1;
                        dp[x.first][mask] = min (dp[x.first][mask], dp[i][mask - (1 << x.first)] + x.second);
                    }
                }
        }
    for(int i = 0; i < n; i++)
        if(dpp[i][stateNo]) {
            for (auto x : graph[i])
                if(x.first == startingNode) {
                    foundCycle = 1;
                    minimCost = min(minimCost, dp[i][stateNo] + x.second);
                }
        }
}

int main() {
    readGraph();

    hamilton();

//    printDpp();
    if(foundCycle)
        out << minimCost;
    else
        out << "Nu exista solutie";
    return 0;
}