考虑将奶牛和牧草放在一起,根据鲜嫩程度排序,那么显然就可以发现一个贪心策略:每一头奶牛一定选择当前剩余的最便宜且符合条件的牧草,然后用一个set维护价格即可
1 #include<bits/stdc++.h> 2 using namespace std; 3 struct ji{ 4 int id,f,m; 5 }a[200005]; 6 multiset<int>s; 7 int n,m; 8 long long ans; 9 bool cmp(ji x,ji y){ 10 return (x.f>y.f)||(x.f==y.f)&&(x.m>y.m); 11 } 12 int main(){ 13 scanf("%d%d",&n,&m); 14 for(int i=1;i<=n+m;i++){ 15 scanf("%d%d",&a[i].m,&a[i].f); 16 a[i].id=i; 17 } 18 sort(a+1,a+n+m+1,cmp); 19 for(int i=1;i<=n+m;i++) 20 if (a[i].id>n)s.insert(a[i].m); 21 else{ 22 set<int>::iterator it=s.lower_bound(a[i].m); 23 if (it==s.end()){ 24 printf("-1"); 25 return 0; 26 } 27 ans+=(*it); 28 s.erase(it); 29 } 30 printf("%lld",ans); 31 }
原文:https://www.cnblogs.com/PYWBKTDA/p/11846828.html