当前位置: 首页 > 工具软件 > Pimp3 > 使用案例 >

POJ2490 Pimp My Ride 状压DP

柴茂材
2023-12-01

POJ2490 Pimp My Ride

/*状压DP 遍历二进制表示的所有状态dp[(1<<n)-1]为最优值
状态转移方程:dp[k|(1<<i)]=min(dp[k|(1<<i)],dp[k]+sum)
657MS	 508K	
*/
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int MAX=15;
const int INF=0x3f3f3f3f;
int a[MAX][MAX],dp[1<<MAX];
int main ()
{
    int case_=0,case_num,n;
    scanf ("%d",&case_num);
    while (++case_<=case_num)
    {
        memset(dp,INF,sizeof (dp));
        scanf ("%d",&n);
        for (int k=0;k<n;k++)
            for (int i=0;i<n;i++)
            scanf ("%d",&a[k][i]);
        dp[0]=0;
        for (int k=0;k<(1<<n);k++)//遍历二进制000~111的所有状态
            for (int i=0;i<n;i++)
            {
                if ((k&(1<<i))==0)//判断i+1位是否为0
                {
                    int sum=a[i][i];
                    for (int j=0;j<n;j++)//判断其余位是否为0
                        if ((k&(1<<j))>0)//注意为>0
                            sum+=a[i][j];
                    dp[k|(1<<i)]=min(dp[k|(1<<i)],dp[k]+sum);//k|1<<i所能达到的最优值
                }
            }
        printf ("Scenario #%d:\nYou have officially been pimped for only $%d\n\n",case_,dp[(1<<n)-1]);
    }
    return 0;
}

 类似资料: