hdu 2639 Bone Collector II

背包问题的第k大值

背包数组另开一维存储第k大值,每次优化时也优化这个维度

#include 
#include 
#include 
#include <string>
using namespace std;



int mmax(int a, int b){

    return a>b ? a : b;
}


int main()
{
    int p;
    cin >> p;
    while (p--){
        int m, n, t;
        int dis[1001][31] = { 0 };
        cin >> m >> n >> t;
        int cost[101] = { 0 };
        int value[101] = { 0 };
        for (int i = 1; i <= m; i++){
            cin >> value[i];
        }
        for (int i = 1; i <= m; i++){
            cin >> cost[i];
        }
        for (int i = 1; i <= m; i++){
            for (int j = n; j >= cost[i]; j--){
                int x[31] = { 0 };
                int y[31] = { 0 };
                for (int k = 1; k <= t; k++){
                    x[k] = dis[j][k];
                    y[k] = dis[j - cost[i]][k] + value[i];
                }
                int a = 1;
                int b = 1;
                int c;
                for (c = 1; c <= t && (a != t + 1 || b != t + 1);){
                    
                    if (x[a] > y[b]){
                        dis[j][c] = x[a];
                        a++;
                    }
                    else {
                        dis[j][c] = y[b];
                        b++;
                    }
                    if (dis[j][c] == 0){
                        break;
                    }
                    if (dis[j][c] != dis[j][c - 1]){
                        c++;
                    }
                }

                for (; c <= t; c++){
                    dis[j][c] = 0;
                }
            }
        }

        cout << dis[n][t] << endl;
    }


    return 0;
}

 

你可能感兴趣的:(hdu 2639 Bone Collector II)