我为2020第A轮做了一个程序,但是它显示错误的答案和测试集跳过了。这就是问题所在
问题
有N栋房子待售。买第一套房子要花艾的钱.你的预算是B美元。
你能买的房子的最大数量是多少?输入
输入的第一行给出了测试用例的数量,T测试用例紧随其后。每个测试用例都从包含两个整数N和B的一行开始。第二行包含N个整数。第一个整数是Ai,这是第一所房子的成本.输出
对于每个测试用例,输出一行包含用例#x: y,其中x是测试用例编号(从1开始),y是您可以购买的房屋的最大数量。限制
时间限制:每套测试15秒。内存限制: 1GB。1≤T≤100。1≤B≤105。1≤Ai≤1000,适用于所有i.测试集1
1≤N≤100。测试集2
1≤N≤105.示例
输入
3 4 100 20 90 40 90 4 50 30 30 10 3 300 999 999 999
输出
案件#1: 2 #2: 3#3 #3: 0
在示例1中,您的预算为100美元。你可以用20 + 40 = 60美元买第一和第三套房子。在第二个例子中,你的预算是50美元。你可以用30 + 10 + 10 = 50美元买第一、第三和第四套房子。在示例3中,您的预算为300美元。你不能买任何房子(所以答案是0)。
注意:与以前的版本不同,在“启动2020”中,所有测试集都是可见的裁决测试集,这意味着您在提交时立即收到反馈。
我的代码是
T = int(input())
caselist = []
for i in range(T):
x = input()
x = x.split()
N = int(x[0])
B = int(x[1])
l = input()
l = l.split()
temp = []
for j in l:
temp.append(int(j))
temp.sort()
s = 0
n = 0
for k in temp:
s+=k
if s<=B:
n+=1
else:
print('Case #'+str(i+1)+': '+str(n))
break

帮我一下这有什么问题..。谢谢!
发布于 2021-04-18 09:18:37
T = int(input())
for test in range(T):
house = []
input1 = input()
input1 = input1.split()
N = int(input1[0])
B = int(input1[1])
input2 = input()
input2 = input2.split()
for x in input2:
price = int(x)
dictionary = {"house":x,"price":price}
house.append(dictionary)
def myFunc(e):
return e['price']
house.sort(key=myFunc)
spent = 0
purchased = 0
for x in house:
variable1 = x.get('price')
spent += variable1
if spent <= B:
purchased += 1
print(f"Case #{test+1}: {purchased}")通过了样本和两个测试
发布于 2020-03-22 22:30:59
您的代码的问题是,如果您可以购买所有的房子,您没有打印答案,因为您只打印一次总成本超过您的预算。这可以很容易地通过将打印语句移出循环之外,在程序结束时解决。
发布于 2020-05-01 12:50:57
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ar array
int n, b, a[100000];
void solve()
{
cin >> n >> b;
for(int i=0; i<n; ++i)
cin >> a[i];
sort(a, a+n);
int ans=0;
for(int i=0; i<n; ++i) {
if(b>=a[I])
{
b-=a[i];
++ans;
}
}
cout << ans << "\n";
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t, i=1;
cin >> t;
while(t--) {
cout << "Case #" << i << ": ";
solve();
++i;
}
}https://stackoverflow.com/questions/60796608
复制相似问题