Tranvick

Kommivoager

Mar 7th, 2012
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.79 KB | None | 0 0
  1. #include <cstdio>
  2. #include <algorithm>
  3. #define mem(A,X) memset(A,X,sizeof(A))
  4. #define rep(I,B) for (int I=0;I<(B);I++)
  5.  
  6. using namespace std;
  7.  
  8. const int N=14;
  9. const int INF=111111111;
  10.  
  11. int g[N][N],n,f[N][1<<N],ans=INF,p[N][1<<N],pos;
  12.  
  13. int calc(int last,int mask){
  14.     if (f[last][mask]!=-1) return f[last][mask];
  15.     int &res=f[last][mask];
  16.     mask^=1<<last;
  17.     res=INF;
  18.     rep(i,n) if (mask&(1<<i)){
  19.         int q=calc(i,mask)+g[i][last];
  20.         if (q<res){
  21.             res=q;
  22.             p[last][mask|(1<<last)]=i;
  23.         }
  24.     }
  25.     return res;
  26. }
  27.  
  28. int main(){
  29.     scanf("%d",&n);
  30.     rep(i,n) rep(j,n) scanf("%d",&g[i][j]);
  31.     int lim=(1<<n)-1;
  32.     mem(f,255);
  33.     f[0][1]=0;
  34.     rep(i,n){
  35.         int q=calc(i,lim)+g[i][0];
  36.         if (q<ans){
  37.             pos=i;
  38.             ans=q;
  39.         }
  40.     }
  41.     printf("%d\n",ans);
  42.     printf("1 ");
  43.     rep(i,n){
  44.         printf("%d ",pos+1);
  45.         int q=pos;
  46.         pos=p[pos][lim];
  47.         lim^=1<<q;
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment