D. Shop Game
题意:有n个物品 商店卖价 第i个商品a[i] alice卖家 第i个商品b[i] 现在需要alice买一些商品(数量可以为0到n) 然后bob可以免费获得alice的k件商品(自己选) 剩下的商品需要从alice那里买(全部都要买) 问你alice可以获得的最大利润。
算法:贪心
思路:alice先把所有商店价格低于alice价格的都买掉,然后bob从中选择k个alice价格最贵的,然后alice每次少买商店价格最大的一个 若少买的这一个为bob选择的 则从剩下的再选一个最贵的,若不是bob已经选择的 则bob的花费将该物品的alice减去
使用set方法的代码:
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
const int Q = 2e5 + 9;
const ll MOD = 1e9 + 7;
ll a[Q],b[Q];
bool cmp(pair<ll,ll> l,pair<ll,ll> r){
if(l.first==r.first) return l.second<r.second;
else return l.first<r.first;
}
void solve(){
vector<pair<ll,ll>> v;
multiset<ll,greater<ll>> st;
ll n,k;cin>>n>>k;
for (ll i = 1; i <= n; i++)
cin>>a[i];
for (ll i = 1; i <= n; i++)
cin>>b[i];
ll l=0,r=0;//l alice花的钱 r bob花的钱
for (ll i = 1; i <= n; i++)
if(a[i]<b[i]){
l+=a[i];
r+=b[i];
v.push_back({a[i],b[i]});
st.insert(b[i]);
}
sort(v.begin(),v.end(),cmp);
ll cnt=k;
while(cnt-- and st.size()){
r-=*(st.begin());
auto it=st.lower_bound(*st.begin());
st.erase(it);
}
ll ans=0;
ans=max(ans,r-l);
for (ll i = v.size()-1; i >= k; i--)
{
auto it=st.find(v[i].second);
l-=v[i].first;
if(it!=st.end()){
r-=*it;
st.erase(it);
}else{
r-=*st.begin();
st.erase(st.begin());
}
ans=max(ans,r-l);
}
cout<<ans<<"\n";
}
int main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
ll _ = 1;cin>>_;
while(_--){
solve();
}
return 0;
}
使用的优先队列和map的代码:
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
const int Q = 2e5 + 9;
const ll MOD = 1e9 + 7;
ll a[Q],b[Q];
bool cmp(pair<ll,ll> l,pair<ll,ll> r){
if(l.first==r.first) return l.second<r.second;
else return l.first<r.first;
}
void solve(){
vector<pair<ll,ll>> v;
map<ll,ll> mp;
priority_queue<ll> pq;
ll n,k;cin>>n>>k;
for (ll i = 1; i <= n; i++)
cin>>a[i];
for (ll i = 1; i <= n; i++)
cin>>b[i];
ll l=0,r=0;//l alice花的钱 r bob花的钱
for (ll i = 1; i <= n; i++)
if(a[i]<b[i]){
l+=a[i];
r+=b[i];
v.push_back({a[i],b[i]});
mp[b[i]]++;
pq.push(b[i]);
}
sort(v.begin(),v.end(),cmp);
ll cnt=k;
while(cnt-- and pq.size()){
mp[pq.top()]--;
r-=pq.top();
pq.pop();
}
ll ans=0;
ans=max(ans,r-l);
for (ll i = v.size()-1; i >= k; i--)
{
l-=v[i].first;
if(mp[v[i].second]>0){
mp[v[i].second]--;
r-=v[i].second;
}else{
while(mp[pq.top()]==0) pq.pop();
mp[pq.top()]--;
r-=pq.top();
pq.pop();
}
ans=max(ans,r-l);
}
cout<<ans<<"\n";
}
int main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
ll _ = 1;cin>>_;
while(_--){
solve();
}
return 0;
}