Codeforces 774B:Significant Cups 前缀和 + 二分

传送门

题目描述

给你n1个一类物品和n2个二类物品,给你每件物品的重要程度和重量,每类物品必须选一件,如果选了某个物品,那么重要程度大于已选物品的同类物品必须要选上,要求选中物品的总重量不超过给定的重量,求最大重要程度之和

分析

思路比较简单了,写起来也不难
首先比较容易想的是,每类物品肯定是从重要程度最高到重要程度最低依次拿,这样我们就可以枚举第一类物品选到第i个,然后去二分第二类物品能选择的最大数量,然后去更新答案即可
提前用前缀和优化预处理一下即可

代码

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <cstring>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define _CRT_SECURE_NO_WARNINGS
#pragma GCC optimize("Ofast","unroll-loops","omit-frame-pointer","inline")
#pragma GCC option("arch=native","tune=native","no-zero-upper")
#pragma GCC target("avx2")
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
const int INF = 0x3f3f3f3f;
const int N = 1e5 + 10;
int n1,n2,m;
struct Node{
    
    
    int d,w;
}a[N],b[N];
ll da[N],db[N];
ll wa[N],wb[N];

bool cmp(Node A,Node B){
    
    
    if(A.w != B.w)
        return A.w > B.w;
    return A.d < B.d;
}

int main(){
    
    
    scanf("%d%d%d",&n1,&n2,&m);
    for(int i = 1;i <= n1;i++) scanf("%d%d",&a[i].w,&a[i].d);
    for(int i = 1;i <= n2;i++) scanf("%d%d",&b[i].w,&b[i].d);
    sort(a + 1,a + 1 + n1,cmp);
    sort(b + 1,b + 1 + n2,cmp);
    for(int i = 1;i <= n1;i++) {
    
    
        da[i] = da[i - 1] + a[i].d;
        wa[i] = wa[i - 1] + a[i].w;
    }
    for(int i = 1;i <= n2;i++) {
    
    
        db[i] = db[i - 1] + b[i].d;
        wb[i] = wb[i - 1] + b[i].w;
    }
    ll ans = 0;
    for(int i = 1;i <= n1;i++){
    
    
        int l = 1,r = n2;
        while(r  - l > 1){
    
    
            int mid = l + r >> 1;
            if(da[i] + db[mid] <= m) l = mid;
            else r = mid - 1;
        }
        if(da[i] + db[r] <= m){
    
    
            ans = max(wa[i] + wb[r],ans);
        }
        if(da[i] + db[l] <= m){
    
    
            ans = max(wa[i] + wb[l],ans);
        }
    }
    printf("%lld\n",ans);
    return 0;
}

/**
*  ┏┓   ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃       ┃
* ┃   ━   ┃ ++ + + +
*  ████━████+
*  ◥██◤ ◥██◤ +
* ┃   ┻   ┃
* ┃       ┃ + +
* ┗━┓   ┏━┛
*   ┃   ┃ + + + +Code is far away from  
*   ┃   ┃ + bug with the animal protecting
*   ┃    ┗━━━┓ 神兽保佑,代码无bug 
*   ┃        ┣┓
*    ┃        ┏┛
*     ┗┓┓┏━┳┓┏┛ + + + +
*    ┃┫┫ ┃┫┫
*    ┗┻┛ ┗┻┛+ + + +
*/

猜你喜欢

转载自blog.csdn.net/tlyzxc/article/details/112465594
今日推荐