Question
Solution
When we see this question, we will think of the traveling salesman problem. However, each vertex can go through a maximum of two times, so we can use a three-digit representation.
Code
#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <cmath>#include <algorithm>#include <cctype>#include <vector>#define INF 2139062143#define MAX 0x7ffffffffffffff#define del(a,b) memset(a,b,sizeof(a))using namespace std;typedef long long ll;template<typename T>inline void read(T&x){ x=0;T k=1;char c=getchar(); while(!isdigit(c)){if(c==‘-‘)k=-1;c=getchar();} while(isdigit(c)){x=x*10+c-‘0‘;c=getchar();}x*=k;}const int maxn=15;int dis[maxn][maxn];int dp[60000][maxn];int poww[15];void _init() { poww[0]=1; for(int i=1;i<=10;i++) poww[i]=poww[i-1]*3; return;}int query(int s,int k) { return s/poww[k]%3;}int add(int x,int k) { return x+poww[k];}int n,m;bool check(int x) { for(int i=0;i<n;i++) if(!query(x,i)) return 0; return 1;}int main(){ _init(); while(~scanf("%d %d",&n,&m)) { del(dis,127);del(dp,127); for(int i=1,u,v,w;i<=m;i++) { read(u),read(v),read(w);--u,--v; dis[u][v]=min(dis[u][v],w); dis[v][u]=min(dis[v][u],w); } for(int i=0;i<n;i++) dp[add(0,i)][i]=0; int ans=INF; for(int s=0;s<poww[n];s++) { for(int i=0;i<n;i++) { if(!query(s,i)) continue; for(int j=0;j<n;j++) { if(j==i||query(s,j)==2||dis[i][j]==INF) continue; dp[add(s,j)][j]=min(dp[s][i]+dis[i][j],dp[add(s,j)][j]); } if(check(s)) ans=min(ans,dp[s][i]); } } if(ans==INF) printf("-1\n"); else printf("%d\n",ans); } return 0;}
View code
HDU 3001 (triplicate)