hdu_5691_Sitting in Line(状压DP)

时间:2021-11-04 14:37:01

题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=5691

题意:中文,不解释

题解:设dp[i][j]表示当前状态为i,以第j个数为末尾的最忧解,然后dp下去就行了

 #include<cstdio>
#define F(i,a,b) for(int i=a;i<=b;i++)
inline void up(int &x,int y){if(x<y)x=y;} int t,n,dp[<<][],a[],b[],inf=-(<<),end,ans,ic=; int main(){
scanf("%d",&t);
while(t--){
scanf("%d",&n),end=(<<n)-,ans=inf;
F(i,,n)scanf("%d%d",a+i,b+i),b[i]++;
F(i,,end)F(j,,n)dp[i][j]=inf;
F(i,,n)if(!b[i]||b[i]==)dp[<<(i-)][i]=;
F(i,,end){
int have=__builtin_popcount(i);//返回该数的二进制1的个数
F(j,,n)if(dp[i][j]>inf)
F(k,,n)if(j==k||(b[k]&&b[k]!=have+)||i&<<(k-))continue;
else up(dp[i|<<(k-)][k],dp[i][j]+a[j]*a[k]);
}
F(i,,n)up(ans,dp[end][i]);
printf("Case #%d:\n%d\n",ic++,ans);
}
return ;
}