HDU3001 Travelling

http://acm.hdu.edu.cn/showproblem.php?pid=3001

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.

 

题意:从任一点出发,走完n个点,每个点最多访问2次,求最短总路程。

思路:每个点只能访问1次就是经典tsp问题,不限制访问次数的话floyd预处理一下,而这道题是限制最多两次,那么用三进制状压dp。

不能直接用位运算了,得用数组模拟。

求出3^i,i∈[0,10],最大是3^10=59049。0~3^10-1就可以表示10位3进制数。

s的第i位2变为1,1变为0,就是s-fac(i)

因为起点固定而终点不固定,所以状态设计必须是以...为起点的。

设f(i,s):现在在i,访问情况压位在s中,对应的最小总路程。

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
#define INF 0x3f3f3f3f

int n,m,d[15][15],f[15][60005];
int fac[15],num[60005][15];

void init()
{
	int x,y;
	fac[0]=1;
	for(int i=1;i<=10;i++)fac[i]=fac[i-1]*3;
	for(int s=0;s<fac[10];s++)
	{
		int i=s;
		for(int j=0;j<10;j++)num[s][j]=i%3,i/=3;
	}
}

void debug()
{
	for(int s=0;s<fac[n];s++)
	{
		for(int v=0;v<n;v++)printf("position:%d,bit:%d,f:%d\n",s,f[v][s]);
	}
}

int dp()
{
	memset(f,INF,sizeof(f));
	int minn=INF;
	for(int i=0;i<n;i++)f[i][fac[i]]=0;//搞清楚两维不要反了 
	for(int s=0;s<fac[n];s++)
	{
		bool ok=1;
		for(int v=0;v<n;v++)
		{
			if(num[s][v]==0){ok=0;continue;}
			for(int u=0;u<n;u++)			//u->v 
			{
				if(num[s-fac[v]][u]==0)continue;
				f[v][s]=min(f[v][s],f[u][s-fac[v]]+d[u][v]);
			}
		}
		if(ok)for(int i=0;i<n;i++)minn=min(minn,f[i][s]);
	}
	return minn;
}

int main()
{
//	freopen("input.in","r",stdin);
	init();
	int x,y,z;
	while(cin>>n>>m)
	{
		memset(d,INF,sizeof(d));
		while(m--)
		{
			cin>>x>>y>>z;
			x--;y--;	//把1~n变成0~n-1 
			d[y][x]=d[x][y]=min(d[x][y],z);
		}
		int minn=dp();
		if(minn!=INF)cout<<minn<<endl;
		else cout<<-1<<endl;
	}
//	debug();
	return 0;
}

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值