ACM学习历程—ZOJ3471 Most Powerful(dp && 状态压缩 && 记忆化搜索 && 位运算)

Description

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

 

这个题目对于每个粒子有存在和消失两种状态,自然总的状态数有2^n种。

对于某种状态,如果用普通的表示,自然有dp[0][1][0]……[1](其中1表示存在,0表示消失),因为每个粒子只有0和1两种值,此处采用二进制进行状态压缩。

接下来考虑对于某个状态10001011,如果第一1要变成0,自然是考虑这个粒子和现存的粒子进行碰撞,然后找能达到的最大值。我们记这个值为GetMax(state, now)(其中state是当前二进制状态,now是由1转为0的那一位)。

于是考虑状态转移方程,对于状态10001,必然由状态11001或10101或10011转换而来,自然对于state,可以由某个0位变成1的状态forestate转换而来。所以:

dp[state] = max{dp[forestate] + GetMax(forestate, now)}

此处采用记忆化搜索进行求解。初始状态M = (1<<n)^0。

 

代码:

#include <iostream>

#include <cstdio>

#include <cstdlib>

#include <cstring>



using namespace std;



int n, M;

int p[15][15];

int dp[1500];



void Input()

{

    memset(dp, 0, sizeof(dp));

    for (int i = 1; i <= n; ++i)

        for (int j = 1; j <= n; ++j)

            scanf("%d", &p[i][j]);

    M = (M<<n)^0;

}



int GetMax(int state, int now)

{

    int Max = 0;

    for (int i = 0; i < n; ++i)

        if (state&(1<<i))

            Max = max(Max, p[i+1][now]);

    return Max;

}



void Dfs(int state)

{

    if (state == M)

    {

        dp[state] = 0;

        return;

    }

    int Max = 0, t;

    for (int i = 0; i < n; ++i)

    {

        if ((state&(1<<i)) == 0)

        {

            if (dp[state|(1<<i)] == 0)

                Dfs(state|(1<<i));

            t = dp[state|(1<<i)] + GetMax(state, i+1);

            Max = max(Max, t);

        }

    }

    dp[state] = Max;

}



int Work()

{

    int ans = 0;

    for (int i = 0; i < n; ++i)

    {

        Dfs(1<<i);

        ans = max(ans, dp[1<<i]);

    }

    return ans;

}



int main()

{

    //freopen("test.in", "r", stdin);

    while (scanf("%d", &n) != EOF && n)

    {

        Input();

        printf("%d\n", Work());

    }

    return 0;

}

 

你可能感兴趣的:(ACM)