您的位置:首页 > 其它

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

2015-05-01 21:07 411 查看
给定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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: