#include <bits/stdc++.h> #define N 300010 #define PII pair<int, int> using namespace std; typedef long long LL; int n, m, a[N], c[N], t, d; LL ans = 0; priority_queue<PII, vector<PII>, greater<PII> > Q; int main(){ scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++){ scanf("%d", &a[i]); } for (int i = 1; i <= n; i++){ scanf("%d", &c[i]); Q.push(make_pair(c[i], i)); } for (int i = 1; i <= m; i++){ scanf("%d%d", &t, &d); if (d <= a[t]){ a[t] -= d; printf("%lld ", 1LL * d * c[t]); } else { bool flag = false; LL ans = 1LL * a[t] * c[t]; d -= a[t]; a[t] = 0; while (!Q.empty()){ while (!Q.empty() && a[Q.top().second] == 0) Q.pop(); if (Q.empty()) break; PII now = Q.top(); if (d <= a[now.second]){ a[now.second] -= d; ans += 1LL * d * now.first; flag = true; printf("%lld ", ans); break; } else { ans += 1LL * a[now.second] * now.first; d -= a[now.second]; a[now.second] = 0; Q.pop(); } } if (!flag){ puts("0"); } } } }
以上是标准程序,只用了155ms,而下面的我的代码用了904ms。差距还是很大的,仔细看,发现是细节的优化。
#include<iostream> #include<queue> #include<algorithm> #define pii pair<int,int> using namespace std; int num[100005]; int price[100005]; typedef long long LL; priority_queue<pii,vector<pii>,greater<pii> > q; int main(){ int n,m; cin>>n>>m; for(int i=1;i<=n;i++) cin>>num[i]; for(int i=1;i<=n;i++){ cin>>price[i]; q.push(make_pair(price[i],i)); } for(int i=0;i<m;i++){ int t,d; cin>>t>>d; LL sum=0; int remain=d; if(num[t]>=d){ sum+=1LL*d*price[t]; num[t]-=d; remain=0; } else{ sum+=1LL*num[t]*price[t]; remain-=num[t]; num[t]=0; } while(remain>0){ if(q.empty()){ cout<<0<<endl; break; } pii f=q.top(); if(num[f.second]>remain){ sum+=1LL*remain*f.first; num[f.second]-=remain; remain=0; } else{ sum+=1LL*num[f.second]*f.first; remain-=num[f.second]; num[f.second]=0; q.pop(); } } if(remain==0) cout<<sum<<endl; } return 0; }