Jogging Trails
bitwise DP
#include <iostream>
#include <cstring>
#include <climits>
#include <cstdio>
#define INF INT_MAX
#define sf(a) scanf("%d", &a)
#define set(b, pos) ( b | (1 << pos) )
#define off(b, pos) ( b & ~( 1 << pos) )
#define test(b, pos) (b & (1 << pos) )
using namespace std;
int v, e, st, en, wt, weight, bits;
int graph[15][15];
int deg[15]; //stores degree of a node
int memo[1 << 15];
int solve(int bits)
{
if(memo[bits] >= 0)
return memo[bits];
int ans = INF;
int b;
for(int i = 0; i < v; i++)
{
for(int j = i + 1; j < v; j++)
{
if(test(bits, i) && test(bits, j))
{
b = bits;
b = off(b, i);
b = off(b, j);
ans = min(ans, solve(b) + graph[i][j]);
}
}
}
return memo[bits] = ans;
}
//finds the shortest distance between every node
void floyd()
{
for(int k = 0; k < v; k++ )
{
for(int i = 0; i < v; i++ )
{
for(int j = 0; j < v; j++ )
{
if(graph[i][k] != INF && graph[k][j] != INF)
graph[i][j] = min(graph[i][k]+graph[k][j], graph[i][j]);
}
}
}
}
int main()
{
while(scanf("%d %d,", &v, &e) == 2)
{
for(int i = 0; i < v; i++)
{
for(int j = 0; j < v; j++)
{
graph[i][j] = INF;
}
}
memset(deg, 0, sizeof(deg));
weight = 0;
bits = 0;
for(int i = 0; i < e; i++)
{
sf(st); sf(en); sf(wt);
st--, en--;
graph[st][en] = graph[en][st] = min(graph[st][en], wt);
weight += wt;
deg[st]++, deg[en]++;
}
floyd();
//sets 1 for each node that has odd degree
for(int i = 0; i < v; i++)
{
if(deg[i] & 1)
{
bits = set(bits, i);
}
}
memset(memo, -1, sizeof(memo));
memo[0] = 0;
weight += solve(bits);
cout << weight << endl;
}
return 0;
}
Comments
Post a Comment