题解:CF1238G Adilbek and the Watering System
考虑到后面的人不能给前面的需求送水,我们从前往后考虑。
考虑先设计一个朴素贪心,我们就让每个人把水加满然后往后跑。
这个算法问题在于一个人加的水后面可能会被另一个价格更低的人加的水替换掉。
于是考虑反悔贪心,不妨维护一个水量与价格构成的集合,从前往后考虑,每考虑到一个人就把他的水全部加进去,假若水量和大于
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int maxn = 1e6+114;
const int inf = 1e9;
int n,m,c,c0;
multiset< pair<int,int> > S;
int sum;
int t[maxn],a[maxn],b[maxn];
int p[maxn];
bool cmp(int x,int y){
return t[x]<t[y];
}
int ans;
bool cost(int cst){
int x=cst;
while(x>0){
if(S.size()==0) return false;
pair<int,int> tp=(*S.begin());
S.erase(S.find(tp));
sum-=tp.second;
int flow=min(tp.second,x);
tp.second-=flow,x-=flow;
ans+=flow*tp.first;
if(tp.second>0) S.insert(tp),sum+=tp.second;
}
return true;
}
void ins(int A,int B){
S.insert(make_pair(B,A));
sum+=A;
while(sum>c){
pair<int,int> tp=(*S.rbegin());
sum-=tp.second;
S.erase(S.find(tp));
if(sum<c){
tp.second=c-sum;
sum+=tp.second;
S.insert(tp);
}
}
}
set<int> T;
void work(){
sum=0;
ans=0;
T.clear();
T.insert(0);
S.clear();
cin>>n>>m>>c>>c0;
for(int i=1;i<=n;i++){
cin>>t[i]>>a[i]>>b[i];
p[i]=i;
T.insert(t[i]);
}
T.insert(m);
sort(p+1,p+n+1,cmp);
int now=0;
ins(c0,0);
for(int x:T){
if(x==m) break;
while(now<n&&t[p[now+1]]==x) now++,ins(a[p[now]],b[p[now]]);
if(cost((*T.upper_bound(x))-x)==false){
cout<<"-1\n";
return ;
}
}
cout<<ans<<'\n';
return ;
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
int t;
cin>>t;
while(t--) work();
return 0;
}
/*
1
2 3 5 1
2 1 1
1 4 3
*/