**Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7128 Accepted Submission(s): 2297
**
Problem Description
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
Source
2009 Multi-University Training Contest 11 - Host by HRBEU
Recommend
gaojie
动规 状压DP
看到点数就会想到状压,然而题目限制每个城市不能经过超过两次,二进制难以表示——那就用三进制表示!
(其实刚开始的想法是二进制相邻两位表示一个城市的到达状态,然而那样1<<20的数组范围吃不消)
除了三进制以外,这题和普通的状压求最短路没啥差别
/*by SilverN*/
#include
#include
#include
#include
#include
#include
using namespace std;
const int mxn=;
int read(){
int x=,f=;char ch=getchar();
while(ch<'' || ch>''){if(ch=='-')f=-;ch=getchar();}
while(ch>='' && ch<=''){x=x*+ch-'';ch=getchar();}
return x*f;
}
int f[][],b[];
int n,m;
int mp[][];
int t[][];
void init(){
for(int i=;i<;i++){
int tmp=i;
for(int j=;j<;j++){
t[i][j]=tmp%;
tmp/=;
}
}
return;
}
int main(){
int i,j,k,u,v,w;
b[]=;
for(i=;i<;i++)b[i]=b[i-]*;
init();
while(scanf("%d%d",&n,&m)!=EOF){
memset(mp,0x3f,sizeof mp);
memset(f,0x3f,sizeof f);
for(i=;i<=m;i++){
u=read();v=read();w=read();
mp[u][v]=mp[v][u]=min(mp[u][v],w);
}
for(i=;i<=n;i++){
f[b[i]][i]=;
}
int ans=0x3f3f3f3f;
int ed=b[n+]-;
for(i=;i<=ed;i++){
bool all=;
for(j=;j<=n;j++){
if(!t[i][j]){
all=;continue;
}
for(k=;k<=n;k++){
if(j==k)continue;
if(t[i][k]>)continue;
f[i+b[k]][k]=min(f[i+b[k]][k],f[i][j]+mp[j][k]);
}
}
if(all){
for(j=;j<=n;j++)
ans=min(ans,f[i][j]);
}
}
if(ans==0x3f3f3f3f)ans=-;
printf("%d\n",ans);
}
return ;
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章