2021秋招顺丰8.20笔试

服务器:
小A有n台服务器,第i个服务器拥有ai的带宽。有m个客户来租服务器,第i 个客户至少需要带宽为bi的服务器,并且愿意花ci元作为预算。(若不能租出则为0),小A可以拒绝一些人,现在问小A的服务器最多能组多少钱?
输入:
3 4
1 2 3
2 1
3 2
3 3
1 1
输出:
5
思路:
参照租金贪心即可,租金相等的话,优先租给带宽需求小的客户。
代码:

#include<bits/stdc++.h>
using namespace std;
//比较器,按租金优先排前面;租金相等的时候,带宽需求少的排在前面(容易满足)
bool cmp(const pair<int,int>& a,const pair<int,int>& b){
    
    
    if(a.second == b.second){
    
    
        return a.first < b.first;
    }
    else if(a.second < b.second){
    
    
        return false;
    }
    else{
    
    
        return true;
    }
}
int main(){
    
    
    int n,m;
    while (cin >> n >> m){
    
    
        vector<int> bandwide(n,0);
        vector<pair<int,int>> guests(m,make_pair(0,0));
        for (int i = 0; i < n; ++i) {
    
    
            cin >>bandwide[i];
        }
        for (int i = 0; i < m; ++i) {
    
    
            cin >>guests[i].first>>guests[i].second;
        }
        //带宽也需要排序
        sort(bandwide.begin(),bandwide.end());
        sort(guests.begin(),guests.end(),cmp);
        int maxval = 0;
        for (int i = 0; i < m; ++i) {
    
    
            //用lower_bound函数找到排序数组中的,第一个>=val的迭代器
            auto it = lower_bound(bandwide.begin(),bandwide.end(),guests[i].first);
            //不等于
            if(it != bandwide.end()){
    
    
                maxval += guests[i].second;
                bandwide.erase(it);
            }
        }
        cout<< maxval<<endl;
    }
}

赏金:
有n个任务,每个任务用l,r,w来表示任务开始,结束时间,以及可以获得的金钱。克里斯是个贪心的人,在任务不冲突的情况之下最多可以获得多少金钱?
输入:
3
1 3 5
2 7 3
5 10 1
输出:
6
思路:
动态规划
状态定义:dp[i]表示前i+1项任务所能获得的最大收益。
转移方程:第i+1项任务可以接在前IndexCanPut(i)项任务的后面:
dp[i] =max(dp[i-1],dp[IndexCanPut(i)]+ arr[i].money)
第i+1项任务不能接在前面的任务后面:
dp[i] =max(dp[i-1],arr[i].money)
代码:

#include<bits/stdc++.h>
using namespace std;

struct task{
    
    
    int l,r,money;
};

typedef vector<task> task_arr;

int IndexCanPut(task_arr& arr,int i){
    
    
    for (int j = i-1; j >= 0 ; --j) {
    
    
        if(arr[j].r <= arr[i].l)
            return j;
    }
    return -1;
}
bool cmp(task a,task b){
    
    
    return a.r < b.r;
}

int task_sort(task_arr &arr){
    
    
    int N = arr.size();
    sort(begin(arr),end(arr),cmp);
    vector<int> dp(N);
    dp[0] = arr[0].money;
    for (int i = 1; i < N; ++i) {
    
    
        int inc_profit = arr[i].money;
        int l =IndexCanPut(arr,i);
        if(l != -1){
    
    
            inc_profit +=dp[l];
        }
        dp[i] = max(inc_profit,dp[i-1]);
    }
    return dp[N-1];
}
int main(){
    
    
    int n;
    while (cin >> n){
    
    //处理多组输入
        vector<task> tasks(n);
        for (int i = 0; i < n; ++i) {
    
    
            task temp;
            int temp1,temp2,temp3;
            cin >> temp1>>temp2>> temp3;
            temp.l = temp1;
            temp.r = temp2;
            temp.money = temp3;
            tasks[i] = temp;
        }
        cout<< task_sort(tasks)<<endl;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35353824/article/details/108140291