最小汉密尔顿回路问题 状态压缩dp

给定n个顶点做成的图,要求从顶点0出发经过所有点一次然后回到0点的一条权值之和最小的一条路的权值

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
#include <climits>
#include <cstring>
#include <cmath>
#include <map>
#include <set>
#define INF 100000000

using namespace std;

struct node {
	int end;
	int state;
};
int n,m;
int ma[100][100];
int dp[100][1<<16];


int main(){
	
	while(cin >> n >> m){
		for(int i = 0;i < m;i++){
			int x,y,w;
			cin >> x >> y >> w;
			ma[x][y] = w;
			ma[y][x] = w;//如果是有向图只要改下这里
		}
		
		queue<node> que;
		node s;
		s.end = 0;
		s.state = 1;
		dp[s.end][s.state] = 0;
		que.push(s);
		
		while(!que.empty()){
			s = que.front();
			que.pop();
			for(int i = 0;i < n;i++){
				if(ma[s.end][i]){
					if(!(s.state&(1 << (i)))){ //这个点之前没有走过 
						dp[i][s.state^(1 << (i))] = dp[s.end][s.state] + ma[s.end][i];
						que.push(node{i,s.state^(1<<(i))});
					}
				}
			}
		}
		
		
		int ans = INF;
		
		for(int i =  1;i < n;i++){
			if(ma[i][0] && dp[i][(1<<n)-1]){
				ans = min(ans,ma[i][0] + dp[i][(1<<n) - 1]);		
			}
		}
		cout << ans << endl;
		
	}
	return 0;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值