[题解-华为机试] 购物单

购物单

解题思路

较为抽象的01背包问题,

# include 
# include 

using namespace std;

int main()
{
    int N, m;
    cin >> N >> m;
    int value, priority, q;
    int i, j;
    vector> data(m+1, vector(6, 0));

    for(i = 1; i <= m; i++)
    {
        cin >> value >> priority >> q;
        // 是主件
        if(q == 0)
        {
            data[i][0] = value;
            data[i][1] = priority;
        }
        // 第一个附件
        else if(data[q][2] == 0)
        {
            data[q][2] = value;
            data[q][3] = priority;
        }
        else 
        {
            data[q][4] = value;
            data[q][5] = priority;
        }
    }

    vector> dp(m+1, vector(N+1, 0));
    for(i = 1; i <= m; i++)
    {
        for(j = 1; j <= N; j++)
        {
            int value1 = data[i][0]; // 主件
            int value2 = data[i][2]; // 附件1
            int value3 = data[i][4]; // 附件2
        
            int prior1 = data[i][1];
            int prior2 = data[i][3];
            int prior3 = data[i][5];

            if(j >= value1)
            {
                dp[i][j] = max(dp[i-1][j], dp[i-1][j-value1] + value1 * prior1);
            }
            else 
            {
                dp[i][j] = dp[i-1][j];
            }

            if(j >= value1 + value2)
            {
                dp[i][j] = max(dp[i][j], 
                            dp[i-1][j - value1 - value2] + value1 * prior1 + value2 * prior2);
            }

            if(j >= value1 + value3)
            {
                dp[i][j] = max(dp[i][j], 
                            dp[i-1][j - value1 - value3] + value1 * prior1 + value3 * prior3);
            }

            if(j >= value1 + value2 + value3)
            {
                dp[i][j] = max(dp[i][j],
                            dp[i-1][j-value1-value2-value3] + value1 * prior1 + value2 * prior2 + value3 * prior3);
            }
        }
    }
    cout << dp[m][N] << endl;

    return 0;
}

参考

华为机试-牛客网
购物单题解

你可能感兴趣的:(算法题,#,动态规划,华为,算法)