C++代码:
#include<iostream>
#include<algorithm>
#include<conio.h>
const int N=1000005;
using namespace std;
double w[N];//古董的重量数组
int main()
{double c;//载重量cint n;//古董个数ncout<<"请输入载重量c及古董个数n:"<<endl;cin>>c>>n;cout<<"请输入每个古董的重量,用空格分开"<<endl;for(int i=0;i<n;i++){cin>>w[i];}sort(w,w+n);//按古董重量升序排序cout<<"排序后结果"<<endl;for(int i=0;i<n;i++){cout<<w[i]<<endl;}double temp=0.0;//已有古董重量int ans=0;//已装古董个数for(int i=0;i<n;i++){temp+=w[i];if(temp<=c)ans++;elsebreak;}cout<<"能装入的古董的最大数量是Ans=";cout<<ans<<endl;cout<<"能装入的古董的最大重量是temp=";cout<<temp<<endl;getch();return 0;
}
python代码:
print("请输入载重量c及古董个数n:")
c=float(input())
n=int(input())
weight=[]
print("请输入每个古董的重量:")
for i in range(n):a=float(input("该古董重量:"))weight.append(a)
for i in range(n):print(weight[i])
weight.sort()
print("古董重量升序排序后的结果:")
for i in range(n):print(weight[i])
ans=0#已装入的古董个数
tmp=0.0#已装入的古董重量
for i in range(n):tmp += weight[i]if tmp<=c:ans=ans+1else:break
tmp=tmp-weight[-1]
print("根据贪心策略能装入古董最大数量为ans=",ans)
print("根据贪心策略能装入古董最大重量为tmp=",tmp)