Cod sursa(job #1480288)

Utilizator tiby10Tibi P tiby10 Data 2 septembrie 2015 13:36:18
Problema Ciclu hamiltonian de cost minim Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 0.9 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("hamilton.in");
ofstream fout("hamilton.out");
#define MAXN 20
#define pb push_back
#define mp make_pair
#define v first
#define c second
int n, m, low=(1<<30), k;
vector<pair<int, int>> G[MAXN];
int used[MAXN];

int muchie(int a, int b){
    for(auto p : G[a])
        if(p.v == b)
            return p.c;
    return 0;
}

void dfs(int node, int cnt, int cost){
    used[node]=1;
    if(cnt==n){
        k=muchie(node ,0);
        if(k)
            low=min(low, cost+k);
        used[node]=0;;
    }
    for(auto vec : G[node])
        if(!used[vec.v])
            dfs(vec.v, cnt+1, cost+vec.c);

    used[node]=0;
}

int main()
{
    int x, y, z;
    fin>>n>>m;
    while(m--){
        fin>>x>>y>>z;
        G[x].pb(mp(y, z));
    }
    dfs(0, 1, 0);
    low==(1<<30)?fout<<"Nu exista solutie":fout<<low;
	return 0;
}