ZOJ-3471 Most Powerful (State compression)
There are n kinds of atoms. If two kinds of atoms collide, energy will be generated, and one of them will disappear. What is the maximum energy produced by these n kinds of atomic energy?
Solution: use 0 to indicate that the atom has not disappeared, and 1 to indicate that the atom has disappeared, so we can get the state transition equation.
Dp [state | (1 <I)] = max (dp [state | (1 <I)], dp [state] + power [j] [I])
The above equation indicates the maximum energy that can be obtained after the I atom disappears when the j atom is used to collide with the I atom.
Note: The generated energy may be negative.
#include
#include#include
using namespace std;#define N 15#define maxn 1200int power[N][N];int dp[maxn];int n;int main() { while(scanf(%d, &n) != EOF && 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 i = 0; i < (1 << n); i++) for(int j = 0; j < n; j++) { if((i & (1 << j))) continue; for(int k = 0; k < n; k++) { if(!(i & (1 << k)) && k != j) { dp[i | (1 << j)] = max(dp[i | (1 << j)], dp[i] + power[k][j]); } } } int ans = 0; for(int i = 0; i < (1 << n); i++) ans = max(ans, dp[i]); printf(%d, ans); } return 0;}