Description
Give you n citys,the cost of travel from one city to another,you job is to find the minimum cost cycle which travels each city one time.Input
The first line of the input file contains a single integer t(1<=t<=10),the number of test case, followed by the input data for each test case.Each test case consists of two parts,the first part contains a integer n (1<=n<=20),the num of citys ,the second part contains n lines,each lines contain n positive integer,the j_th num in the i_th line means the cost of travel from the i_th city to the j_th city.The cost of travle from the i_th city to j_th city is equal to the cost of travle from the j_th city to i_th city.Output
There should be one line per test case in the output file containing a single integer,the minimum cost you find.Sample Input
1 4 0 30 6 4 30 0 5 10 6 5 0 20 4 10 20 0Sample Output
25Source
思路:
一道状压的经典题了,首先我们考虑为什么用dp求解,对于这道题来说,很明显符合子问题求解的特征,所以我们一定可以用dp解得,对于当前所在的城市,明显有多个城市作为下一个目的地,那么改选择谁呢,这时候就要根据子问题的最优解来选择了,不就是明显的dp吗,至于为什么用状压dp呢,对于每一种状态,我们需要知道还有哪些城市需要去走,如果直接开20维数组会十分麻烦,这时候就可用二进制数来表示状态了。
ac代码:
#include<cstdio> #include<algorithm> #include<cstring> #include<map> #include<queue> #include<iostream> #include<sstream> #include<cmath> #define LL long long #define INF 0x3f3f3f3f using namespace std; const int maxsta = (1<<20); int T,n; int dp[21][maxsta]; int dis[25][25]; string two(int x){ string res = ""; while(x){ int tmp = x%2; res+=tmp+'0'; x/=2; } if(res.size()==0) res+='0'; //reverse(res.begin(),res.end()); return res; } int dfs(int cur,int sta) { if(dp[cur][sta]!=-1) return dp[cur][sta]; dp[cur][sta] = INF; int falg = 0; for(int i = 0;i<n;i++){ if((1<<i)&sta){ //if(i!=cur) // dp[cur][sta] = min(dp[cur][sta],dis[cur][i]+dfs(i,sta^(1<<i)^(1<<cur))); //else dp[cur][sta] = min(dp[cur][sta],dis[cur][i]+dfs(i,sta^(1<<i))); falg = 1; } } if(!falg) dp[cur][sta]=dis[cur][0]; //cout<<dp[cur][sta]<<' '<<cur<<' '<<two(sta)<<endl; return dp[cur][sta]; } int main() { scanf("%d",&T); while(T--){ scanf("%d",&n); memset(dis,0,sizeof(dis)); memset(dp,-1,sizeof(dp)); for(int i = 0;i<n;i++){ for(int j = 0;j<n;j++){ scanf("%d",&dis[i][j]); dis[j][i] = dis[i][j]; } } int mx = (1<<n)-1; dfs(0,mx^1); cout<<dp[0][mx^1]<<endl; } }
The TSP problem SCU - 2842(状压dp,记搜)
最新推荐文章于 2021-01-31 21:24:10 发布