HDU 3001 - Travelling TSP

http://acm.hdu.edu.cn/showproblem.php?pid=3001
#include <cmath>
#include <string>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

template <typename _T>
_T Max(_T a , _T b){
	return (a>b)?(a):(b);
}
template <typename _T>
_T Max(_T a , _T b, _T c){
	return (a>Max(b,c))?(a):(Max(b,c));
}
template <typename _T>
_T Min(_T a , _T b){
	return (a<b)?(a):(b);
}
template <typename _T>
_T Min(_T a , _T b, _T c){
	return (a<Min(b,c))?(a):(Min(b,c));
}

const int inf    = -(1<<30);
const int INF    =  (1<<30);
const int STATE  =  6e4 + 10; //3^10 = 59049
const int M      =  12;
int tri[12] = {0,1,3,9,27,81,243,729,2187,6561,19683,59049};
int dp[STATE][M]; // dp[i][j] 表示了 state[i][0->10]中10个数字的状态 重点落在j城市的最优值
int d[M][M]; // 邻接矩阵
int state[STATE][M]; // state[i][0->10]中10个数字的状态
int n_city,n_seg;

void ternay(){ // 初始化,将状态转换为三进制 state[i]中的前10个表示城市对应状态
	int ter_bound = tri[10+1];
	memset(state,0,sizeof(state));
	for(int i = 0 ; i <= ter_bound ; i++){
		int tmp = i;
		int cnt = 1;
		while(tmp){
			state[i][cnt++] = tmp % 3;
			tmp /= 3;
		}
	}
}


int main(){
	//freopen("in.txt","r",stdin);
	ternay();
	while(~scanf("%d %d" , &n_city, &n_seg) ){
		for(int i = 0 ; i < M ; i++)
			for(int j = 0 ; j < M ; j++)
				d[i][j] = INF;
		for(int i = 0; i < STATE ; i++)
			for(int j = 0 ; j < M ; j++)
				dp[i][j] = INF;
		for (int i = 0,a,b,len ; i < n_seg ; i++){
			scanf("%d %d %d",&a,&b,&len);
			d[b][a] = d[a][b] = Min(len,d[a][b]); // 去重边
		}
		int ans = INF;
		for(int i = 1 ; i <= n_city ; i++)  // 如果tri这个状态只有一个城市,那么就以这个城市为起点,显然起点一共为10个
			dp[tri[i]][i] = 0;

		int bound = tri[n_city+1]-1;

		for (int i = 1 ; i <= bound ; i++){
			bool isend = true;
			for(int j = 1 ; j <= n_city ; j++){
				if(state[i][j] == 0) isend = false;		// 这个状态中 还有为0的,即城市没有访问过
				if(dp[i][j] < 0)continue;				// dp[i][j] 这个不是起点,一定是从起点开始dp的

				for(int k = 1 ; k <= n_city ; k++){		// 下一个城市为k
					if(j == k) continue;				// 如果k和i为同一个城市
					if(d[j][k] == INF) continue;		// 去不了下一个城市k 
					if(state[i][k] >= 2) continue;		// 下一个城市k已经访问过2次了
#define NEXT i+tri[k]									//这里要访问下一个k城市,则在当前三进制state:i上+1 等价于 i+tri[k]
					dp[NEXT][k] = Min(dp[NEXT][k], dp[i][j] + d[j][k]); 
#undef NEXT
				}
			}

			if(isend){ // 说明这个状态里面的城市全部访问过了
				for(int k = 1 ; k <= n_city ; k++){
					ans = Min(ans,dp[i][k]);
				}
			}
		}
		if(ans == INF)ans = -1;
		cout << ans << endl;
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值