【NOIP2017提高A组模拟9.5】NYG的背包
Description
Input
Output
Sample Input
输入1:
1
3 5
3 1
4 8
8 3
输入2:
3
7 9269
21366 1233
7178 23155
16679 23729
15062 28427
939 6782
24224 9306
22778 13606
5 22367
17444 5442
16452 30236
14893 24220
31511 13634
4380 29422
7 18700
25935 4589
24962 9571
26897 14982
20822 2380
21103 12648
32006 22912
23367 20674
Sample Output
输出1:
Yes
输出2:
Yes
Yes
No
Data Constraint
题解
题意
有个背包,每放进一个物品就会增大一定的值,问能否把所有物品装下
分析
显然贪心
先放b-a>=0的
再按照物体的体积从大到小放
code
#include<cstdio>
#include<cctype>
#include<cstdlib>
#include<algorithm>
#define R register int
using namespace std;
const int N=100010;
struct rd{
long long a,b;
}a[N],b[N];
struct Node{long long w;int pos;};
struct node{
int cnt;
Node q[N];
void push(Node x){
q[++cnt]=x;
int y=cnt;
while(y>1&&q[y].w>q[y>>1].w)
q[0]=q[y],q[y]=q[y>>1],q[y>>1]=q[0],y>>=1;
}
void pop(){
q[1]=q[cnt--];
int y=1,x;
while((y*2<=cnt&&q[y*2].w>q[y].w)||(y*2<cnt&&q[y*2+1].w>q[y].w)){
if(y*2<cnt&&q[y*2+1].w>q[y*2].w)x=y*2+1;
else x=y<<1;
q[0]=q[x],q[x]=q[y],q[y]=q[0],y=x;
}
}
}q;
int T,n;
long long v;
inline void read(long long &x){
x=0;char ch=getchar();
while(!isdigit(ch))ch=getchar();
while(isdigit(ch))x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
}
bool cmp1(rd x,rd y){return x.a<y.a;}
bool cmp2(rd x,rd y){return x.b>y.b;}
int main(){
scanf("%d",&T);
while(T--){
R j=1,tot=0;
q.cnt=0;
scanf("%d%lld",&n,&v);
for(R i=1;i<=n;++i)read(a[i].a),read(a[i].b);
sort(a+1,a+1+n,cmp1);
for(j=1;j<=n&&a[j].a<=v;++j)q.push(Node{a[j].b-a[j].a,j});
while(q.cnt&&v>0){
while(q.cnt&&a[q.q[1].pos].a>v)q.pop();
if(!q.cnt||q.q[1].w<0)break;
v+=q.q[1].w,++tot,q.pop();
while(j<=n&&a[j].a<=v)q.push(Node{a[j].b-a[j].a,j}),++j;
}
j=0;
while(q.cnt)b[++j].a=a[q.q[1].pos].a,b[j].b=a[q.q[1].pos].b,q.pop();
sort(b+1,b+1+j,cmp2);
for(R i=1;i<=j&&b[i].a<=v;++i)v+=b[i].b-b[i].a,++tot;
if(tot==n)printf("Yes\n");
else printf("No\n");
}
}