HDU-3177(贪心)
Crixalis's Equipment
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3633 Accepted Submission(s): 1460
Problem Description
Crixalis - Sand King used to be a giant scorpion(蝎子) in the deserts of Kalimdor. Though he's a guardian of Lich King now, he keeps the living habit of a scorpion like living underground and digging holes.Someday Crixalis decides to move to another nice place and build a new house for himself (Actually it's just a new hole). As he collected a lot of equipment, he needs to dig a hole beside his new house to store them. This hole has a volume of V units, and Crixalis has N equipment, each of them needs Ai units of space. When dragging his equipment into the hole, Crixalis finds that he needs more space to ensure everything is placed well. Actually, the ith equipment needs Bi units of space during the moving. More precisely Crixalis can not move equipment into the hole unless there are Bi units of space left. After it moved in, the volume of the hole will decrease by Ai. Crixalis wonders if he can move all his equipment into the new hole and he turns to you for help.
Input
The first line contains an integer T, indicating the number of test cases. Then follows T cases, each one contains N + 1 lines. The first line contains 2 integers: V, volume of a hole and N, number of equipment respectively. The next N lines contain N pairs of integers: Ai and Bi.
0<T<= 10, 0<V<10000, 0<N<1000, 0 <Ai< V, Ai <= Bi < 1000.
0<T<= 10, 0<V<10000, 0<N<1000, 0 <Ai< V, Ai <= Bi < 1000.
Output
For each case output "Yes" if Crixalis can move all his equipment into the new hole or else output "No".
Sample Input
2
20 3
10 20
3 10
1 7
10 2
1 10
2 11
Sample Output
Yes
No
题意:有n个物品,每个物品有一个自己的体积a,还有一个移动时所需的空间b。给定一个总的空间v,问能否将n件物品移动到空间内。
思路:贪心。
考虑物品i和物品j放入时。
如果先i后j,所需空间: if bi-ai >= bj ,所需空间为bi。if bi-ai < bj, 所需空间为ai+bj。
如果先j后i,所需空间: if bj-aj >= bi,所需空间为bj。if bj-aj < bi, 所需空间为aj+bi;
有3种情况,bi与aj+bi,bj与ai+bj,ai+bj与aj+bi。
对于ai+bj与aj+bi:
如果ai+bj<aj+bi,则选先i后j。即bi-ai>bj-aj,差值大的排前边。差值相同的无所谓了。
对于bi与aj+bi:
选先i后j。这种情况时,bi-ai >= bj,那么bi-ai>bj-aj,同样满足差值大的排前边。
读入数据后根据数据对差值从小到大排序。
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 using namespace std; 5 6 #define maxn 1010 7 struct node{ 8 int a, b; 9 }no[maxn]; 10 11 int t,v,n; 12 13 int cmp(node& no1, node& no2){ 14 return (no1.b-no1.a) > (no2.b-no2.a); 15 } 16 17 int main() 18 { 19 scanf("%d", &t); 20 while(t--){ 21 scanf("%d%d", &v, &n); 22 for (int i = 0; i < n; i++){ 23 scanf("%d%d", &no[i].a, &no[i].b); 24 } 25 26 //根据差值从小到大排序 27 sort(no, no + n, cmp); 28 29 //从第一个开始计算所需空间 30 int vneed = 0; 31 bool flag = false; 32 for(int i = 0; i < n; i++){ 33 //一旦发现放入第i件物品时所需空间大于总空间,break 34 if(no[i].b + vneed > v){ 35 flag = true; 36 break; 37 } 38 vneed += no[i].a; 39 } 40 41 if(flag) printf("No\n"); 42 else printf("Yes\n"); 43 } 44 return 0; 45 }

浙公网安备 33010602011771号