【贪心】完全背包问题
贪心算法一般思路:从顶向下,大问题分解为小问题,小问题求最优解(一般都要排序)
1.排队接水
题目描述
有 n 个人在一个水龙头前排队接水,假如每个人接水的时间为 Ti ,请编程找出这 n 个人排队的一种顺序,使得 n 个人的平均等待时间最小。
输入格式
第一行为一个整数 n。
第二行 n 个整数,第 i 个整数 Ti 表示第 i 个人的等待时间 Ti。
输出格式
输出文件有两行,第一行为一种平均时间最短的排队顺序;第二行为这种排列方案下的平均等待时间(输出结果精确到小数点后两位)。
输入输出样例:
输入
10
56 12 1 99 1000 234 33 55 99 812
输出
3 2 7 8 1 4 9 6 10 5
291.90
(题目来源:洛谷P1223 排队接水)
思路分析
要让人等待时间尽可能少,就需要使排在最前面的人接水时间最短,后面的人等待时间才会短。
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <stdbool.h>
using namespace std;
int a[1005]= {0};
int b[1005]= {0};
int main()
{
int n,i,j,x;
scanf("%d",&n);
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
b[i]=a[i];
}
sort(a,a+n);
for(i=0; i<n-1; i++)
{
for(j=0; j<n; j++)
{
if(a[i]==b[j])
{
cout<<j+1<<" ";
b[j]=-1;
}
}
}
for(j=0; j<n; j++)
{
if(a[n-1]==b[j])
{
cout<<j+1;
b[j]=1000008;
}
}
cout<<endl;
double sum=0;
x=0;
for(i=0;i<n-1;i++)
{
x+=a[i];
sum+=x;
}
sum=sum/n;
printf("%.2lf",sum);
return 0;
}
2.淘淘摘苹果
题目描述
又是一年秋季时,陶陶家的苹果树结了 n 个果子。陶陶又跑去摘苹果,这次他有一个 a 公分的椅子。当他手够不着时,他会站到椅子上再试试。
这次与 NOIp2005 普及组第一题不同的是:陶陶之前搬凳子,力气只剩下 s 了。当然,每次摘苹果时都要用一定的力气。陶陶想知道在 s<0 之前最多能摘到多少个苹果。
现在已知 n 个苹果到达地上的高度 xi ,椅子的高度 a,陶陶手伸直的最大长度 b,陶陶所剩的力气 s,陶陶摘一个苹果需要的力气 yi ,求陶陶最多能摘到多少个苹果。
输入格式
第 1 行:两个数 苹果数 n,力气 s。
第 2 行:两个数 椅子的高度 a,陶陶手伸直的最大长度 b。
第 3 行~第 3+n-1 行:每行两个数 苹果高度 xi ,摘这个苹果需要的力气 yi 。
输出格式
只有一个整数,表示陶陶最多能摘到的苹果数。
输入输出样例
输入
8 15
20 130
120 3
150 2
110 7
180 1
50 8
200 0
140 3
120 2
输出
4
说明
n<=5000,a<=50,b<=200,s<=1000,x<=280,y<=100.
(题目来源:洛谷P1478 淘淘摘苹果升级版)
思路分析:
苹果的高度首先要是能摘到的,想要摘到尽可能多的苹果,就要先摘耗费体力少的苹果。
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <stdbool.h>
using namespace std;
int apple[6000]= {0};
int main()
{
int n,s,a,b,h,i;
int x,y;
cin>>n>>s;
cin>>a>>b;
h=a+b;
if(n==0)
{
cout<<"0";
return 0;
}
int j=0,cnt=0;
for(i=1; i<=n; i++)
{
cin>>x>>y;
if(x<=h)
{
apple[j]=y;
j++;
}
}
sort(apple,apple+j);
i=0;
while(s-apple[i]>=0)
{
s=s-apple[i];
i++;
cnt++;
}
if(s<0)
cnt--;
cout<<cnt;
return 0;
}
(本篇作为学习笔记自用)