Recently, researchers on Mars have discovered N powerful atoms. All of them are different. These atoms have some properties. When two of these atoms collide, one of them disappears and a lot of power is produced. Researchers know the way every two atoms perform when collided and the power every two atoms can produce.
You are to write a program to make it most powerful, which means that the sum of power produced during all the collides is maximal.
Input
There are multiple cases. The first line of each case has an integer N (2 <= N <= 10), which means there are N atoms: A1, A2, ... , AN. Then N lines follow. There are N integers in each line. The j-th integer on the i-th line is the power produced when Ai and Aj collide with Aj gone. All integers are positive and not larger than 10000.
The last case is followed by a 0 in one line.
There will be no more than 500 cases including no more than 50 large cases that N is 10.
Output
Output the maximal power these N atoms can produce in a line for each case.
Sample Input
2
0 4
1 0
3
0 20 1
12 0 1
1 10 0
0
Sample Output
4
22
题意:每两个原子碰撞后一个消失且释放大量能量,现在给你N个原子,以及一个矩阵。在矩阵的第 i 行 第 j 列 的元素表示i 原子 撞 j 原子后 释放的能量(j 原子 会消失)。问你这N个原子能够产生的最大能量。
思路:明显的状态压缩。用1表示原子是否被撞后消失。用0表示原子没有被其它原子撞击。(撞击要分 主动 和 被动 不要混淆了)
用dp[ i ] 表示 i 状态下释放的最大能量。则对于N个原子,有状态数目 1<< N个。(其实还可以预处理掉一部分,我没有预处理)
power[ i ][ j ]记录 i 原子撞 j 原子释放的能量。
枚举所有1<<N个状态,对每个状态S枚举任意匹配的两个原子i 和 j
有状态转移方程:
dp[S^(1<<j)] = max(dp[S^(1<<j)], dp[S] + power[i][j]);
j 没有被撞击的状态 i 和 j 都没有被撞击的状态 + i 撞击 j 产生的能量
AC代码:
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; int N; int dp[1<<11];//存储该状态下的最大能量 int power[11][11]; int main() { while(scanf("%d", &N), N) { for(int i = 0; i < N; i++) for(int j = 0; j < N; j++) scanf("%d", &power[i][j]); memset(dp, 0, sizeof(dp)); for(int S = (1<<N)-1; S >= 0; S--) { for(int i = 0; i < N; i++) { if(S & (1<<i))//包含i状态 { for(int j = 0; j < N; j++) { if(S & (1<<j) && i != j)//j 和 i不重复 且 S包含j状态 dp[S^(1<<j)] = max(dp[S^(1<<j)], dp[S] + power[i][j]); } } } } int ans = 0; for(int i = 0; i < (1<<N)-1; i++) ans = max(ans, dp[i]); printf("%d\n", ans); } return 0; }