Cod sursa(job #933342)

Utilizator testerx93Daniel Carnaru testerx93 Data 29 martie 2013 21:02:52
Problema Ciclu hamiltonian de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.65 kb
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <cstring>
#define NMAX 20
#define MMAX 400
using namespace std;

vector<int> stack, G[NMAX];
int seen[NMAX], seenVertices, localCost;
int N, M, totalCost, cost[NMAX][NMAX];

void input()
{
	int i, a, b, c;
	scanf("%d%d", &N, &M);
	memset(seen, -1, sizeof(seen));
	for (i=0; i<M; ++i)
	{
		scanf("%d%d%d", &a, &b, &c);
		G[a].push_back(b);
		cost[a][b] = c;
	}
}

void edgeSort(const int &vertex, int left, const int &right)
{
	int i=left, j=right, aux, m=cost[vertex][G[vertex][G[vertex].size()>>1]];
	while (i <= j)
	{
		while (cost[vertex][G[vertex][i]] < m)
			++i;
		while (cost[vertex][G[vertex][j]] > m)
			--j;
		if (i <= j)
		{
			aux = G[vertex][i];
			G[vertex][i] = G[vertex][j];
			G[vertex][j] = aux;
			++i; --j;
		}
	}
	if (i < right) edgeSort(vertex, i, right);
	if (left < j)  edgeSort(vertex, left, j);
}

/*void Hamilton(int startVertex)
{
	stack.push_back(startVertex);
	while (stack.size()>0 && seenVertices<=N)
	{
		int current = stack[stack.size()-1];
		for (int i=0; i<G[current].size(); ++i)
		{
			seen[current] = 1;
			++seenVertices;
			int adjancted = G[current][i];
			if (seen[adjancted]==0 || (adjancted==startVertex && seenVertices==N))
			{
				stack.push_back(adjancted);
				totalCost += cost[current][adjancted];
			}
			if (adjancted==startVertex && seenVertices==N)
				return;
            G[current][i] = G[current][G[current].size()-1];
            G[current].pop_back();
			current = stack[stack.size()-1];
		}
		stack.pop_back();
		seen[current] = 0;
		//--seenVertices;
		totalCost -= cost[stack[stack.size()-1]][current];
	}
}*/

void Hamilton(int startVertex, int &localCost)
{
    ++seenVertices;
    if (seenVertices == N+1)
    {
        if (totalCost < localCost)
            totalCost = localCost;
        return;
    }
    for (int i=0; i<G[startVertex].size(); ++i)
    {
        int adjancted = G[startVertex][i];
        if (seen[adjancted]==-1 || (adjancted==0 && seenVertices==N))
        {
            localCost += cost[startVertex][adjancted];
            seen[adjancted] = startVertex;
            Hamilton(adjancted, localCost);
            localCost -= cost[startVertex][adjancted];
            //--seenVertices;
        }
    }
}

void output()
{
	if (totalCost == 0)
        printf("Nu exista solutie.");
    else printf("%d", totalCost);
}

int main()
{
    freopen("hamilton.in", "r", stdin);
    freopen("hamilton.out", "w", stdout);
	input();
	for (int i=0; i<N; ++i)
        edgeSort(i, 0, G[i].size()-1);
    Hamilton(0, localCost);
	output();
	return 0;
}