列表

详情


NC25033. [USACO 2007 Dec G]Gourmet Grazers

描述

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.

输入描述

* 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

输出描述

* Line 1: A single integer which is the minimum cost to satisfy all the cows. If that is not possible, output -1.

示例1

输入:

4 7
1 1
2 3
1 4
4 2
3 2
2 1
4 3
5 2
5 4
2 6
4 4

输出:

12

说明:

Cow 1 eats grass 2 at cost 2, cow 2 eats grass 3 at cost 4, cow 3 eats grass 6 at cost 2, and cow 4 eats grass 7 at cost 4, for a total cost of 12.

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++14(g++5.4) 解法, 执行用时: 148ms, 内存消耗: 7888K, 提交时间: 2019-07-13 20:33:26

#include<stdio.h>
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define fd(i,a,b) for(int i=a;i>=b;i--)
#include<algorithm>
#include<set>
using namespace std;
int n,m,now;
long long ans;
struct cow{
	int a,b;
	bool operator <(const cow &x)const{
		return b>x.b;
	}
}c[110000],g[110000];
multiset<int> q;
int main(){
	scanf("%d%d",&n,&m);
	fo(i,1,n) scanf("%d%d",&c[i].a,&c[i].b);
	sort(c+1,c+n+1);
	fo(i,1,m) scanf("%d%d",&g[i].a,&g[i].b);
	sort(g+1,g+m+1);
	now=1;
	fo(i,1,n){
		while(now<=m&&g[now].b>=c[i].b){
			q.insert(g[now].a);
			now++;
		}
		auto it=q.lower_bound(c[i].a);
		if (it==q.end()){
			printf("-1\n");
			continue;
		}
		ans+=*it;
		q.erase(it);
	}
	printf("%lld\n",ans);
	return 0;
}

C++11(clang++ 3.9) 解法, 执行用时: 262ms, 内存消耗: 4208K, 提交时间: 2020-03-29 13:17:10

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+100;
#define ll long long
struct node
{
	int x,y;
}a[N],b[N];
multiset<int>st;
int cmp(node a,node b)
{
	if(a.y==b.y) return a.x<b.x;
	return a.y>b.y; 
}
int main()
{
	int n,m;
	cin>>n>>m;
	for(int i=0;i<n;i++)
	cin>>a[i].x>>a[i].y;
	for(int i=0;i<m;i++)
	cin>>b[i].x>>b[i].y;
	sort(a,a+n,cmp);
	sort(b,b+m,cmp);
	int idx=0;
	ll ans=0;
	for(int i=0;i<n;i++)
	{
		while(idx<m&&b[idx].y>=a[i].y) st.insert(b[idx].x),idx++;
		auto it=st.lower_bound(a[i].x);
		if(it==st.end())
		{
			cout<<-1<<endl;
			exit(0);
		 } 
		 else ans+=*it;
		 st.erase(it);
	}
	cout<<ans<<endl;
	return 0;
}

上一题