VJ - N - Travelling

原题网址 N - Travelling

After coding so many days,Mr Acmer wants to have a good rest.So travelling is the best choice!He has decided to visit n cities(he insists on seeing all the cities!And he does not mind which city being his start station because superman can bring him to any city at first but only once.), and of course there are m roads here,following a fee as usual.But Mr Acmer gets bored so easily that he doesn't want to visit a city more than twice!And he is so mean that he wants to minimize the total fee!He is lazy you see.So he turns to you for help.

题意:给你一个图,从一个点到另一个点有路,需要花费。起点是任意的,要求每个点最多走两次,把所有的点遍历完一遍,费用最小

Input

There are several test cases,the first line is two intergers n(1<=n<=10) and m,which means he needs to visit n cities and there are m roads he can choose,then m lines follow,each line will include three intergers a,b and c(1<=a,b<=n),means there is a road between a and b and the cost is of course c.Input to the End Of File.

Output

Output the minimum fee that he should pay,or -1 if he can't find such a route.

Sample Input

2 1
1 2 100
3 2
1 2 40
2 3 50
3 3
1 2 3
1 3 4
2 3 10

Sample Output

100
90
7 

状压dp , 因为原题有三种情况, 所以要用3进制来压缩状态, 要预处理three[]数组;

题解代码:

在下面有两种方法:
一种dp[i+three[k]][k] = min(dp[i+three[k]][k], dp[i][j]+g[j][k]);  由前面遍历后面

另一种dp[i][k] = min(dp[i][k], dp[i-three[k]][j] + g[k][j]);  由后面遍历前面

/*
https://vjudge.net/contest/441637#problem/N
N - Travelling
*/

#include<bits/stdc++.h>
using namespace std;
const int N = 11;
const int inf = 0x3f3f3f3f;

int three[12];
int g[N+1][N+1];
int dp[400000][N+1];
int n, m;
void init() {
	three[1] = 1;
	for(int i = 2; i <= 11; i ++) {
		three[i] = three[i-1] * 3;
	}
}
int solve() {
	int ans = inf;
	for(int i = 1; i <= n; i ++){
		dp[three[i]][i] = 0; // 每个城市到自己的距离为0 
	}
	for(int i = 1; i < three[n+1]; i ++) {
		bool flag = true;
		for(int j = 1; j <= n; j ++) {
			//cout << i << " " << three[j] << endl;
			if((i/three[j])%3 == 0) {
				flag = false;
				continue;
			}
			for(int k = 1; k <= n; k ++){
				if((i/three[k])%3 == 0) continue; // 访问两次后,就不可以访问了
				//dp[i+three[k]][k] = min(dp[i+three[k]][k], dp[i][j]+g[j][k]);
				dp[i][k] = min(dp[i][k], dp[i-three[k]][j] + g[k][j]);
			}
		}
		if(flag){
			for(int j = 1; j <= n; j ++){
				ans = min(dp[i][j], ans);
			}
		}
	}
	return ans;
}
int main() {
	init();
	while(cin >> n >> m) {
		memset(g, inf, sizeof(g));
		memset(dp, inf, sizeof(dp));
		for(int i = 1; i <= m; i ++) {
			int a, b, v;
			cin >> a >> b >> v;
			g[a][b] = g[b][a] = min(g[a][b], v);  // 生成邻接矩阵
		}
		if(solve() == inf)   cout << -1 << endl;
		else  cout << solve() << endl;
	}
	return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值