题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=3177

思路:刚开始的想法是挪的时候占体积大的先进,如果挪的体积相同,则放的时候体积小的先进,结果wrong了,举一个反例

40 2

20 30

2 19

AC代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>
#include <cctype>
const int inf = 0x3f3f3f3f;//1061109567
typedef long long LL;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
struct node
{
int zhang;
int need;
}a[1010];
bool cmp(node a,node b)
{
return a.need + b.zhang < a.zhang + b.need;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int v,n;
scanf("%d%d",&v,&n);
int sum = 0;
for(int i=0; i<n; i++)
{
scanf("%d%d",&a[i].need,&a[i].zhang);
sum += a[i].need;
}
if(sum > v)
{
printf("No\n");
continue;
}
sort(a,a+n,cmp);
int i;
for(i=0; i<n; i++)
{
if(v >= a[i].zhang)
v -= a[i].need;
else
break;
}
if(i == n)
printf("Yes\n");
else
printf("No\n");
}
return 0;
}

错误代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>
#include <cctype>
const int inf = 0x3f3f3f3f;//1061109567
typedef long long LL;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
struct node
{
int zhang;
int need;
}a[1010];
bool cmp(node a,node b)
{
if(a.zhang != b.zhang)
return a.zhang > b.zhang;
else
return a.need < b.need;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int v,n;
scanf("%d%d",&v,&n);
int sum = 0;
for(int i=0; i<n; i++)
{
scanf("%d%d",&a[i].need,&a[i].zhang);
sum += a[i].need;
}
if(sum > v)
{
printf("No\n");
continue;
}
sort(a,a+n,cmp);
int i;
for(i=0; i<n; i++)
{
if(v >= a[i].zhang)
v -= a[i].need;
else
break;
}
if(i == n)
printf("Yes\n");
else
printf("No\n");
}
return 0;
}