1. 程式人生 > >【狀壓dp】Most Powerful

【狀壓dp】Most Powerful

last algorithm out 我只 res queue str nbsp digi

[ZOJ3471]Most Powerful

Time Limit: 2 Seconds Memory Limit: 65536 KB

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


Author: GAO, Yuan
Contest: ZOJ Monthly, February 2011

題目大意:給你一些元素,這些元素碰撞後會產生其中消失的物品的能量(你可以自己決定哪一個消失),求最後剩1個元素的最大能量釋放值

試題分析:比較基礎的一道狀壓dp 貌似在dp中我只能說狀壓dp有基礎題,好弱QAQ

     dp[S]表示序列消到狀態為S的時候的最大釋放能量值。

     可得出如下轉移方程(因為是消失,所以應該從(1<<N)-1到1枚舉): dp[S]=max(dp[S],dp[S+(1<<(k-1))]+make[j][k]);

     其中k代表消失的能量,j代表剩下的能量,前提是S包含j,不包含k,k!=j

代碼:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<vector>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std;

inline int read(){
	int x=0,f=1;char c=getchar();
	for(;!isdigit(c);c=getchar()) if(c==‘-‘) f=-1;
	for(;isdigit(c);c=getchar()) x=x*10+c-‘0‘;
	return x*f;
}
const int MAXN=100001;
const int INF=999999;
int N,M;
int dp[MAXN];
int e[1001][1010];

int main(){
    N=read();
    while(1){
    	if(!N) break;
    	memset(dp,0,sizeof(dp));
    	for(int i=1;i<=N;i++){
    		for(int j=1;j<=N;j++)
    		    e[i][j]=read();
		}
		int ans=0;
		for(int i=(1<<N)-2;i>=1;i--){
			for(int j=1;j<=N;j++){
				if(!((i>>(j-1))&1)) continue;
				for(int k=1;k<=N;k++){
					if(k==j||((i>>(k-1))&1)) continue;
					dp[i]=max(dp[i],dp[i+(1<<(k-1))]+e[j][k]);
				}
			}
		}
		for(int i=1;i<=N;i++) ans=max(ans,dp[1<<(i-1)]);
		printf("%d\n",ans);
		N=read();
	}
}

【狀壓dp】Most Powerful