转载自:http://blog.csdn.net/xindoo/article/details/9173949
暴力TLE
1 #include <iostream> 2 #include <string.h> 3 #include <algorithm> 4 5 using namespace std; 6 7 int vis[17]; 8 int n, ans, sum; 9 int map[19][19]; 10 11 void dfs(int x) 12 { 13 if (x == n+1) 14 { 15 ans = max(ans, sum); 16 return; 17 } 18 for (int i = 1; i <= n; i++) 19 { 20 if (vis[i] == 0) 21 { 22 sum += map[x][i]; 23 vis[i] = 1; 24 dfs(x+1); 25 vis[i] = 0; 26 sum -= map[x][i]; 27 } 28 } 29 } 30 int main() 31 { 32 int t; 33 cin >> t; 34 for (int kase = 1; kase <= t; kase++) 35 { 36 cin >> n; 37 for (int i = 1; i <= n; i++) 38 for (int j = 1; j <= n; j++) 39 cin >> map[i][j]; 40 sum = 0; 41 ans = 0; 42 memset(vis, 0, sizeof(vis)); 43 dfs(1); 44 cout << "Case " << kase << ": " << ans << endl; 45 } 46 return 0; 47 }
状态压缩+dp
//2013-06-25-22.05 #include <iostream> #include <string.h> #include <algorithm> #include <stdio.h> using namespace std; const int maxn = 1<<16; int vis[17]; int n, ans, sum; int map[19][19]; int dp[maxn]; int dfs(int x, int d) { if (x == 0) return 0; if (dp[x]) return dp[x]; for (int i = 0; i < n; i++) { if (x&(1<<i)) dp[x] = max(dfs(x^(1<<i), d-1)+map[i+1][d], dp[x]); } return dp[x]; } int main() { int t; cin >> t; for (int kase = 1; kase <= t; kase++) { cin >> n; for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) cin >> map[i][j]; memset(dp, 0, sizeof(dp)); ans = dfs((1<<n)-1, n); printf("Case %d: %d\n", kase, ans); } return 0; }
时间: 2024-10-06 08:39:27