首页 > 代码库 > 旅行商(n<15)

旅行商(n<15)

http://icpc.ahu.edu.cn/OJ/Problem.aspx?id=420

#include <cstdio>#include <cstdlib>#include <cstring>#include <algorithm>#include <cmath>#include <stack>#include <queue>#include <vector>#include <map>#include <string>#include <iostream>using namespace std;const int INF=0xfffffff;int Min(int a,int b){    return a>b?b:a;}int dp[20][1<<16];int n;int Map[20][20];int dfs(int x,int y){    if(x==0&&y==0)return 0;    if(dp[x][y]) return dp[x][y];    int ans=INF;    for(int i=0;i<n;i++){        if(y&(1<<i)){            int tem=dfs(i,y-(1<<i)) + Map[x][i];            ans=Min(ans,tem);        }    }    return dp[x][y]=ans;}int cf(int a,int b){    int ans=1;    for(int i=0;i<b;i++)        ans*=a;    return ans;}int main(){    while(cin>>n){        memset(dp,0,sizeof(dp));        for(int i=0;i<n;i++)        for(int j=0;j<n;j++)        if(i!=j) Map[i][j]=INF;else Map[i][j]=0;        for(int i=0;i<n;i++)            for(int j=0;j<n;j++)            scanf("%d",&Map[i][j]);        for(int i=0;i<n;i++){            dp[i][0]=Map[0][i];        }        int k=cf(2,n)-1-1;        cout<<dfs(0,k)<<endl;    }    return 0;}