E.Education ( multiset的二分查找 )

E.Education ( multiset的二分查找 )

題目鏈接:https://vjudge.net/problem/Gym-101606E

題意:有n批人,第i批有ai個人,有m個公寓,第i個公寓可以容納pi人,租金是ri,要求從這m個公寓裏選出n個給這n批人,且總租金最小,輸出第i批人應該租的公寓編號。

思路:貪心的考慮,肯定優先選擇最便宜的公寓,那麼這個公寓給誰呢?應該給小於這個公寓人數且最接近它的( 聯想到upper_bound() - 1 )。公寓好說,存結構體裏按照租金排序。n批人呢?我們應該對這n批人的需求排序,再進行二分查找。但是考慮到每次選擇完一個公寓就應該從二分列表裏刪除,但數組是不好做刪除操作的。我們考慮用multiset.

 

 

代碼:

#include <bits/stdc++.h>

using namespace std;

int n,m;
struct node {
    int weight,money,id;
}a[5005];
struct nop {
    int id,people;
    bool operator<( const nop&b )const {
        return people<b.people;
    }
}t;
int ans[5005];
multiset<nop> s;

int rule( node a, node b )
{
    return a.money<b.money;
}

int main()
{
    cin >> n >> m;
    for ( int i=0; i<n; i++ ) {
        scanf("%d",&t.people);
        t.id=i+1;
        s.insert(t);
    }
    for ( int i=0; i<m; i++ ) scanf("%d",&a[i].weight);
    for ( int i=0; i<m; i++ ) scanf("%d",&a[i].money);
    for ( int i=0; i<m; i++ ) a[i].id=i+1;
    sort(a,a+m,rule);
    for ( int i=0; i<m; i++ ) { // 從最便宜的公寓開始枚舉
        int now = a[i].weight;
        t.people = now;
        if ( s.size()==0 ) break;
        multiset<nop>::iterator it = s.upper_bound(t); // 找到滿足當前公寓+1的批次
        if ( it!=s.begin() ) it --; // --到滿足當前公寓的批次
        if ( (*it).people<=now ) {
            ans[ (*it).id ] = a[i].id;
            s.erase(it);
        }
    }
    if ( s.size()==0 ) for ( int i=1; i<=n; i++ ) cout << ans[i] << " ";
    else cout << "impossible" << endl;

    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章