列表

详情


NC13882. Knapsack Problem

描述

Today HH becomes a shopper, and he wants to buy a lot.
HH has a bag that can carry at most w kilograms things in total, and he has d dollars.
Now he wants to buy n items,the ith item weights wi kilogram and costs ci dollars.
HHis not good at math so he asks you to tell him whether he can buy all the things and carry them with the bag.

输入描述

The first line contains an positive integer T(1≤T≤10), represents there are T test cases. 
For each test case: 
The first line contains three positive integers n,w,d(1≤n≤100,1≤w≤100,1≤d≤100) - the number of items HH wants to buy, the max weight that his bag can carry, and the money he has. 
The second line contains n integers w1,w2…wn(1≤wi≤100). The third line contains n integers c1,c2…cn(1≤ci≤100).

输出描述

For each test case, output one line "YES" (without quotes) if HH is possible to buy all the items and carry them in his bag, and "NO" (without quotes) otherwise.

示例1

输入:

2
4 12 17
1 2 4 5
5 4 6 2
4 11 17
1 2 4 5
5 4 6 2

输出:

YES
NO

说明:

In the first example all the items cost 17 dollars in total and weight 12 kilograms in total, HH has enough money and his bag can carry 12 kilogram things.

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++11(clang++ 3.9) 解法, 执行用时: 10ms, 内存消耗: 488K, 提交时间: 2020-02-11 19:41:30

#include<bits/stdc++.h>
using namespace std;
int main()
{int t,w,n,d;
cin>>t;
while(t--){
	cin>>n>>d>>w;
	int p=0,q=0,x,y;
	for(int i=0;i<n;i++){
	  cin>>x;
	  p+=x;
	}
	for(int i=0;i<n;i++){
	  cin>>y;
	  q+=y;
	}
	if(p<=d&&q<=w) cout<<"YES"<<endl;
	else cout<<"NO"<<endl;
}
}

C(clang11) 解法, 执行用时: 3ms, 内存消耗: 368K, 提交时间: 2020-11-26 12:25:43

#include<stdio.h>
int t,n,c,w;
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d",&n,&w,&c);
int x;
for(int i=1;i<=n;i++)
{
scanf("%d",&x);
w-=x;
}
for(int i=1;i<=n;i++)
{
scanf("%d",&x);
c-=x;
}
if(w>=0&&c>=0)printf("YES\n");
else printf("NO\n");
}
return 0;
 } 

Python3 解法, 执行用时: 35ms, 内存消耗: 4528K, 提交时间: 2022-06-22 14:11:54

T=int(input())
for i in range(T):
    c,w,d=map(int,input().split())
    a=map(int,input().split())
    b=map(int,input().split())
    if sum(a)<=w and sum(b)<=d:
        print("YES")
    else:
        print("NO")

上一题