https://codeforces.com/problemset/problem/1379/C
思路:考虑答案情况,假如a[i]都买了,剩下的钱肯定挑一个b[i]最大的买完。我们注意到,最优的答案应该是剩下的钱都买某个物品了。那么我们可以枚举某个物品,对于其他>这个物品的b[i]的贡献能就都拿,剩下都拿这个物品的b[i].
注意一下二分的边界。找大于等于的第一个位置再-1
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=1e5+1000;
typedef long long LL;
typedef pair<LL,LL>P;
inline LL read(){LL x=0,f=1;char ch=getchar(); while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
P a[maxn];
LL b[maxn],sum[maxn];
int main(void){
cin.tie(0);std::ios::sync_with_stdio(false);
LL T;cin>>T;
while(T--){
LL n,m;cin>>n>>m;
for(LL i=0;i<m+10;i++) sum[i]=0,a[i].first=a[i].second=b[i]=0;
for(LL i=1;i<=m;i++){
cin>>a[i].first>>a[i].second;
}
sort(a+1,a+1+m);
for(LL i=1;i<=m;i++) {
sum[i]=sum[i-1]+a[i].first;
b[i]=a[i].first;
}
LL ans=0;
for(LL i=1;i<=m;i++){///枚举该种物品拿最终的b
LL x=lower_bound(b+1,b+1+m,a[i].second)-b-1;///注意大于等于a[i].second的位置再-1找最大的<a[i].second的位置
LL res=0;
if(n>=m-x){///能拿的>剩下的总数
if(i>x){///本身也在里面
LL num=m-x;
res+=( sum[m]-sum[m-num])+(n-num)*(a[i].second);
}
else{
LL num=m-x;
res+=(sum[m]-sum[m-num])+(n-num-1)*(a[i].second)+a[i].first;
}
}
else{
res+=(sum[m]-sum[m-n]);
}
ans=max(ans,res);
}
cout<<ans<<"\n";
}
return 0;
}