链接:
https://codeforces.ml/problemset/problem/1539/D
题意:
第一行n,n种商品,单价均为2,打折后单价均为1,第i+1行数据表示第i个需要买的数量和能使这件商品打折所需的购买量(买到足量<一共>就打折)
输入
3
3 4
1 3
1 5
输出量
8
输入
5
2 7
2 8
1 2
2 4
1 8
输出量
12
解:
先满足好打折的
跟着WA加if了属于是
双指针
实际代码:
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long int ll;
struct sp
{
ll need;
ll half;
}sz[100005];
bool PX(const sp &a,const sp &b)
{
if(a.half<b.half) return 1;
else if(a.half==b.half)
{
if(a.need<b.need) return 1;
else return 0;
}
else return 0;
}
int main()
{
int n;
cin>>n;
for(int f=1;f<=n;f++)
{
cin>>sz[f].need>>sz[f].half;
}
sort(sz+1,sz+n+1,PX);
int mao1=1,mao2=n;
ll ans=0,num=0;
//cout<<"--------------------"<<endl;
/*
for(int f=1;f<=n;f++)
{
cout<<sz[f].need<<" "<<sz[f].half<<endl;
}
*/
for(int i=1;mao1<mao2;i++)
{
//cout<<i<<endl;
if(sz[mao1].need==0) mao1++;
if(sz[mao2].need==0) mao2--;
if(mao1==mao2) break;
if(num>=sz[mao1].half)
{
//cout<<"abuy"<<mao1<<"-"<<sz[mao1].need<<endl;
ans+=sz[mao1].need;
num+=sz[mao1].need;
sz[mao1].need=0;
continue;
}
if(sz[mao1].need==0) mao1++;
if(sz[mao2].need==0) mao2--;
if(mao1==mao2) break;
if(sz[mao2].need<sz[mao1].half-num)
{
//cout<<"bbuy"<<mao2<<"-"<<sz[mao2].need<<endl;
ans+=2*sz[mao2].need;
num+=sz[mao2].need;
//cout<<"ans+="<<2*sz[mao2].need<<endl;
sz[mao2].need=0;
}
else
{
//cout<<"cbuy"<<mao2<<"-"<<sz[mao1].half-num<<endl;
ans+=2*(sz[mao1].half-num);
sz[mao2].need-=(sz[mao1].half-num);
//cout<<"lost"<<mao2<<"-"<<(sz[mao1].half-num)<<endl;
num+=sz[mao1].half-num;
}
if(sz[mao1].need==0) mao1++;
if(sz[mao2].need==0) mao2--;
}
if(num<sz[mao1].half&&sz[mao1].need-(sz[mao1].half-num)>=0)
{
//cout<<"scbuy"<<mao1<<"-"<<(sz[mao1].half-num)<<endl;
ans+=2*(sz[mao1].half-num);
sz[mao1].need-=(sz[mao1].half-num);
num+=(sz[mao1].half-num);
}
//cout<<num<<sz[mao1].half<<endl;
if(num>=sz[mao1].half)
{
//cout<<"last1buy"<<mao1<<"-"<<sz[mao1].need<<endl;
ans+=sz[mao1].need;
}
else
{
//cout<<"last2buy"<<mao1<<"-"<<sz[mao1].need<<endl;
ans+=2*sz[mao1].need;
}
cout<<ans<<endl;
}
限制:
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output