Wannafly挑战赛15 最小化价格(贪心)

题目描述 

现有n组人,m个地点,给出每组人的人数,每个地点可容纳的最大人数和选择的价格
要求一种方式,使得每组人都到一个各不相同的地点,最小化选择的价格
每个队伍的人都要在同一个地方每个地方只能有一个队伍

输入描述:

第一行n,m
第二行n个数,表示每组的人数
接下来m行,每行两个数,表示可容纳的最大人数和选择的价格

输出描述:

输出最小化选择的价格,无解输出-1
示例1

输入

3 4
2 3 4
1 2
2 3
3 4
4 5

输出

12

备注:

所有数据小于1e5

思路:贪心选择,先安排人多的队伍,从能盛下去的里面选择最便宜的,然后依次给每个队伍这样安排,用优先队列选择地点即可.

代码:

#include<bits/stdc++.h>
using namespace std;
 
const int maxn = 1e6+5;
 
struct node
{
    int sum;
    int cost;
    bool operator < (node b) const
	{
		return cost> b.cost;	
	}
} b[maxn];
 
int n,m;
int a[maxn];
 
bool cmp(node x,node y)
{
    return x.sum> y.sum;
}
 
int main()
{
    cin>>n>>m;
    for(int i = 1;i<= n;i++)
        scanf("%d",&a[i]);
 
    for(int i = 1;i<= m;i++)
        scanf("%d %d",&b[i].sum,&b[i].cost);
 
    sort(a+1,a+n+1);
    sort(b+1,b+m+1,cmp);
 
    priority_queue<node> q;
    int j = 1;
    long long ans = 0;
    for(int i = n;i>= 1;i--)
    {
        for(;j<= m;j++)
        {
            if(b[j].sum< a[i])
                break;
            q.push(b[j]);
        }
 
        if(q.empty())
        {
            ans = -1;
            break;
        }
 
        ans+= q.top().cost;
        q.pop();
    }
 
    cout<<ans<<endl;
 
    return 0;
}

猜你喜欢

转载自blog.csdn.net/nka_kun/article/details/80290820
今日推荐