Cod sursa(job #986922)

Utilizator Cosmin1490Balan Radu Cosmin Cosmin1490 Data 19 august 2013 19:09:33
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
using namespace std;
  
const string file = "hamilton";
  
const string infile = file + ".in";
const string outfile = file + ".out";

const int INF = 0x3f3f3f3f;
int N;
int M;

int Sol;

vector<vector<pair<int, int> > > G;

vector<vector<int> > DP;


int main()
{
	ifstream fin(infile.c_str());

	fin >> N >> M;


	G.resize(N);
	DP.resize(1 << N, vector<int>(N, INF));

	for(int i = 0; i < M; i++)
	{
		int x,y,c;
		fin >> x >> y >> c;

		G[y].push_back(make_pair(x, c));

	}

	fin.close();

	DP[1][0] = 0;

	for(int i = 0; i < 1 << N; i++)
	{
		for(int j = 0; j < N; j++)
		{
			if(i & (1 << j))
			{
				
				for(vector<pair<int, int> >::iterator itr = G[j].begin();
					itr != G[j].end();
					itr++)
				{
					if(i & (1 << itr->first) )
					{
						DP[i][j] = min(DP[i][j], DP[i ^ (1 << j)][itr->first] + itr->second);
					}
				}
			}
		}
	}

	Sol = INF;

	for(vector<pair<int, int> >::iterator itr = G[0].begin();
		itr != G[0].end();
		itr++)
	{
		Sol = min(Sol, DP[(1 << N) - 1][itr->first] + itr->second);
	}
	ofstream fout(outfile.c_str());
	if(Sol == INF)
	{
		fout << "Nu exista solutie\n";
	}
	else
	{
		fout << Sol << "\n";
	}
	fout.close();
}