Description
Input
1 <= T <= 20
1 <= n, v <= 1000
1 <= ai, bi <= 1000
Output
Sample Input
1 4 2 1 2 2 1 3 1 2 3
Sample Output
yes
解题思路:先用结构来存储背包的ai和bi,里面还有一个元素,就是bi-ai的值,我们优先放入bi-ai>0的礼物,如果有多个bi-ai>0,就优先放入小的礼物,具体的实现看下面的代码。
#include<bits/stdc++.h>
using namespace std;
struct gift{
int a,b,d;
};
bool cmp(const gift &x,const gift &y)
{
if(x.d>0&&y.d<0) return true;
else if(x.d<0&&y.d>0) return false;
else return x.a<y.a;
}
gift g[1001];
int main(void)
{
int ncases;
scanf("%d",&ncases);
while(ncases--)
{
int n,vbeg;
scanf("%d%d",&n,&vbeg);
for(int i=0;i<n;i++)
{
scanf("%d%d",&g[i].a,&g[i].b);
g[i].d=g[i].b-g[i].a;
}
sort(g,g+n,cmp);
bool flag=true;
for(int i=0;i<n;i++)
{
if(vbeg<g[i].a)
{
flag=false;
break;
}
vbeg+=g[i].d;
}
printf("%s\n",flag?"yes":"no");
}
return 0;
}