题目大意:
给出一个n个顶点的无向图,请寻找一条从顶点0出发,遍历其余顶点一次且仅一次、最后回到顶点0的回路——即Hamilton回路。
解题报告:
状压dp...
AC代码:
1 #include<bits/stdc++.h> 2 #define numm ch-48 3 #define pd putchar(' ') 4 #define pn putchar(' ') 5 #define pb push_back 6 #define fi first 7 #define se second 8 #define fre1 freopen("1.txt","r",stdin) 9 #define fre2 freopen("3.txt","w",stdout) 10 #define bug cout<<"*******************"<<endl; 11 #define debug(args...) cout<<#args<<"->"<<args<<" "; 12 using namespace std; 13 template <typename T> 14 void read(T &res) { 15 bool flag=false;char ch; 16 while(!isdigit(ch=getchar())) (ch=='-')&&(flag=true); 17 for(res=numm;isdigit(ch=getchar());res=(res<<1)+(res<<3)+numm); 18 flag&&(res=-res); 19 } 20 template <typename T> 21 void write(T x) { 22 if(x<0) putchar('-'),x=-x; 23 if(x>9) write(x/10); 24 putchar(x%10+'0'); 25 } 26 typedef long long ll; 27 typedef unsigned long long ull; 28 const int maxn=22; 29 const int maxm=505; 30 const int mod=1e9+7; 31 const int inv2=500000004; 32 const int inf=0x3f3f3f3f; 33 const ll INF=0x3f3f3f3f3f3f3f3f; 34 const int N=32; 35 int a[maxn][maxn]; 36 int dp[maxn][1<<maxn]; 37 int n,m; 38 int get_hamilton(int n) { 39 for(int i=0;i<n;i++) 40 for(int j=0;j<(1<<n);j++) 41 dp[i][j]=inf; 42 for(int i=0;i<n;i++) ///从i出发,且中途不经过i 43 dp[i][0]=a[i][0]; 44 for(int s=1;s<(1<<n);s++) 45 for(int i=0;i<n;i++) 46 if(!(s>>i&1)) 47 for(int j=0;j<n;j++) 48 if(a[i][j]!=inf&&(s>>j&1)) 49 dp[i][s]=dp[i][s]<(dp[j][s^(1<<j)]+a[i][j])?dp[i][s]:(dp[j][s^(1<<j)]+a[i][j]); 50 return dp[0][(1<<n)-2]; 51 } 52 int main() 53 { 54 // #define local 55 #ifdef local 56 fre1; 57 fre2; 58 #endif // local 59 while(scanf("%d%d",&n,&m)!=EOF) { 60 for(int i=0;i<n;i++) 61 for(int j=0;j<n;j++) 62 a[i][j]=inf; 63 for(int i=1;i<=m;i++) { 64 int u,v,w; 65 read(u),read(v),read(w); 66 a[u][v]=a[u][v]<w?a[u][v]:w; 67 a[v][u]=a[v][u]<w?a[v][u]:w; 68 } 69 int ans=get_hamilton(n); 70 if(ans==inf) puts("no Hamilton circuit"); 71 else write(ans),pn; 72 } 73 return 0; 74 }