题意:
市场上有n种商品,每种商品的价格都是2。现在需要买第i种商品ai件。如果你已经买了bi件商品(不一定是这一种商品),那么此商品价格为1,求最小代价;
思路:
把b[i]升序排列;
如果可以1价格买下,则直接买完;
如果不可以,则购买b[i]最大的直到可以1价格买下该商品或有别的商品开始打折;
这里还采用了双指针,左指针为买到哪个商品,右指针为最大的b[i];
Code:
#include <iostream>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <string>
#include <algorithm>
#include <queue>
#include <utility>
#include <stack>
#include <map>
#include <vector>
#include <set>
#include <iomanip>
#define hz020 return
#define mes memset
#define mec memcpy
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>pii;
const int N = 200010;
const int null = 0x3f3f3f3f;
const ll mod = 998244353;
int n;
struct node
{
ll a,b;
}s[N];
int gcd(int a,int b)
{
return b ? gcd(b,a % b) : a;
}
bool cmp(node x,node y){return x.b < y.b;}
int main()
{
cin >> n;
ll qq = 0;
for(int i = 1;i <= n;i ++) cin >> s[i].a >> s[i].b,qq += s[i].a;
sort(s + 1,s + 1 + n,cmp);
int l = 1,r = n;
ll cnt = 0,sum = 0;
while(cnt != qq)
{
if(s[l].b <= cnt)
{
cnt += s[l].a;
sum += s[l].a;
l ++;
}
else
{
ll idx = min(s[r].a,s[l].b - cnt);
sum += idx * 2;
s[r].a -= idx;
cnt += idx;
if(!s[r].a) r --;
}
}
cout << sum << endl;
hz020 0;
} ```