GESP4级考试语法知识(贪心算法(一))
海盗船代码:
#include<iostream>
#include<algorithm>
using namespace std;
int data[21];
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)
cin>>data[i];
sort(data,data+n);
int temp=0,sum=0;
for(int i=0;i<n;i++)
{
temp+=data[i];
if(temp>500)
{
break;
}
sum++;
}
cout<<sum<<endl;
return 0;
}
排队接水1代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
struct people
{
int num;
int time;
};
people s[1001];
int n;
double sum,ave;
bool cmp(people x,people y)
{
return x.time<y.time;
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>s[i].time;
s[i].num=i;
}
sort(s+1,s+n+1,cmp);
double t=0;
for(int i=2;i<=n;i++)
{
t+=s[i-1].time;
sum+=t;
}
ave=sum/n;
for(int i=1;i<=n;i++)
{
cout<<s[i].num<<" ";
}
printf("\n%.2lf",ave);
return 0;
}