Description
Like so many others, the cows have developed very haughty tastes and will no longer graze on just any grass. Instead, Farmer John must purchase gourmet organic grass at the Green Grass Grocers store for each of his N (1 ≤ N ≤ 100,000) cows.
Each cow i demands grass of price at least Ai (1 ≤ Ai ≤ 1,000,000,000) and with a greenness score at least Bi (1 ≤ Bi ≤ 1,000,000,000). The GGG store has M (1 ≤ M ≤ 100,000) different types of grass available, each with a price Ci (1 ≤ Ci ≤ 1,000,000,000) and a greenness score of Di (1 ≤ Di ≤ 1,000,000,000). Of course, no cow would sacrifice her individuality, so no two cows can have the same kind of grass.
Help Farmer John satisfy the cows' expensive gourmet tastes while spending as little money as is necessary.
Input
* Line 1: Two space-separated integers: N and M.
* Lines 2..N+1: Line i+1 contains two space-separated integers: Ai and Bi
* Lines N+2..N+M+1: Line i+N+1 contains two space-separated integers: Ci and Di
Output
* Line 1: A single integer which is the minimum cost to satisfy all the cows. If that is not possible, output -1.
Sample Input
4 7 1 1 2 3 1 4 4 2 3 2 2 1 4 3 5 2 5 4 2 6 4 4
Sample Output
12
贪心,策略是尽量用便宜的草去满足牛,当一种草可以满足多个牛时选green要求最高的牛。
那么我们先给grass和cow分别升序排序,for(int i=1;i<=M;i++) i枚举一种草,j枚举牛。因为事先grass和cow都排好了序,所以只要grass[i].p>cow[j].p,那么 [1,j] 的cow都满足p比当前枚举到的草小,也就说我们在[1,j] 的cow中找一个green要求最高但是又不超过grass[i].g就可以了。所以我就想到了用一个multiset来存前j头牛的g值,然后按降序排一下(这里有个小小的技巧——set里通常是升序排的,那么我希望降序就在每个数前加个负号)每次用lower_bound查询有没有比grass[i].g小的。
#include <cstdio>
#include <algorithm>
#include <set>
using namespace std;
typedef long long LL;
#define MaxN 100100
struct node
{
int p,g;
bool operator < (node const& a)const
{return g>a.g;}
}cow[MaxN],grass[MaxN];
int N,M;
LL sum=0;
multiset<int> ms;
bool cmp(node a,node b) {return a.p<b.p;}
int main()
{
bool flag=0;
scanf("%d%d",&N,&M);
for(int i=1;i<=N;i++)
scanf("%d%d",&cow[i].p,&cow[i].g);
sort(cow+1,cow+1+N,cmp);
for(int i=1;i<=M;i++)
scanf("%d%d",&grass[i].p,&grass[i].g);
sort(grass+1,grass+1+M,cmp);
int j=1,tot=0;
for(int i=1;i<=M;i++)//选一种草
{
while(j<=N && grass[i].p>=cow[j].p) {ms.insert(-cow[j].g);j++;}//找出所有p满足的牛
multiset<int>::iterator it=ms.lower_bound(-grass[i].g);
if(it!=ms.end())
{
sum+=grass[i].p;
ms.erase(it);
tot++;
if(tot==N) break;
}
}
if(tot<N) printf("-1");
else printf("%I64d",sum);
while(1);
return 0;
}