状态压缩,用二进制数来表示状态,从而达到状态转移的目的。
例题,最短哈密尔顿路径。
https://www.acwing.com/problem/content/93/
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
   | #include<bits/stdc++.h> using namespace std; const int N =20; const int M = 1<<20; const int inf  = INT_MAX/2; int n; int dp[M][N]; int gra[N][N]; int main(void) {     scanf("%d",&n);     for(int i=0;i<n;i++)     {         for(int j=0;j<n;j++)         {             scanf("%d",&gra[i][j]);         }     }     memset(dp,0x3f,sizeof dp);     dp[1][0]=0;     for(int i=0;i<1<<n;i++)     {         for(int j=0;j<n;j++)         {             if((i>>j) &1)             {                 for(int k=0;k<n;k++)                 {                     if(((i-(1<<j))>>k) & 1 )                     {                         dp[i][j] = min(dp[i][j],dp[i-(1<<j)][k]+gra[k][j]);                                              }                 }             }         }     }     printf("%d",dp[(1<<n)-1][n-1]); }
 
  |