1.鸡兔同笼
已经知道共有多少只腿,问至少多少只动物,至多少只动物?
输入:腿的总数
输出: 最大值和最小值
#include <iostream>
using namespace std;
int main(){
int a;
while(scanf("%d", &a)){
int min = 0;
int max = 0;
if(a % 2 == 0){ //是偶数才有解
max = a / 2;
min = a / 4 + (a % 4)/2; //用兔子的个数 + 对4取余后得到的数
}
cout << max;
cout << " " << min;
}
return 0;
}
2.求两个数组差值的最大值
题目:抢手有n支抢,每支抢有攻击力a[i],每个靶子的防御力b[j],用枪射中靶子可得到a[i] - b[j]的奖金。每支抢只能用来杀死一个怪物,会得到a[i] - b[j]的奖金,问如何得到最大的奖金?
(1)算法思路:
a数组从大到小排序
b数组从小到大排序
answer += (a[i] - b[i])
(2)要点注意
1).sort()默认从小到大排序,若想改为从大到小排序,需要自己写一个函数
2).使用sort()函数需要#include <algorithm>
样例输入:
1 //样例的测试数量
2 2 //a数组个数 b数组个数
2 3 //a数组对应的每个值
2 2 //b数组对应的每个值
样例输出:
1 //输出最大奖金
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX = 10001;
long long gun[MAX];
long long thing[MAX];
bool maxToMin(long long a, long long b){
return a > b;
}
int main(){
int caseNumber;
scanf("%d", &caseNumber);
while(caseNumber--){
int n,m;
scanf("%d%d", &n, &m); //n代表抢个数,m代表怪物的个数
for(int i= 0; i < n; i++){
scanf("%d", &gun[i]);
}
for(int j = 0; j < m; j++){
scanf("%d", &thing[j]);
}
//枪从大到小排序
sort(gun,gun+n,maxToMin);
//怪物从小到大排序
sort(thing,thing+m);
long long answer = 0;
for(int i = 0; i<n; i++){
if( i>=m || gun[i] <= thing[i]){ //若抢数量大于怪物数量 或者 抢的值小于等于怪物值 不用减
break;
}else{
answer += (gun[i] - thing[i]);
}
}
cout << answer << endl;
}
return 0;
}
3.区间贪心
输入数据包含多个测试实例,每个测试实例的第一行只有一个整数n(n<=100),表示你喜欢看的节目的总数,然后是n行数据,每行包括两个数据timeStart和timeEnd,分别表示某个节目的开始和结束时间,为简化问题,每个时间都用一个正整数表示。n = 0表示输入结束,不做处理。
(1)算法思想:
1)按照每个节目结束时间从小到大排序,依次寻找满足条件的,把查找到的上一个结束时间赋值给下一个的开始 。
样例输入:
12
1 3
3 4
0 7
3 8
15 19
15 20
8 18
6 12
5 10
4 14
2 9
0
样例输出:
5
代码:
#include <iostream>
#include <algorithm>
using namespace std;
struct Program{
int startTime;
int endTime;
};
const int MAX = 100;
Program arr[MAX];
bool Compare(Program x, Program y){
return x.endTime < y.endTime;
}
int main(){
int n;
while(scanf("%d", &n) != EOF){
if(n == 0){
break;
}
for(int i = 0; i < n; i++){
scanf("%d%d", &arr[i].startTime, &arr[i].endTime);
}
sort(arr, arr+n, Compare); //按照结束时间从小到大排序
int current = 0;
int count = 0;
for(int i = 0; i<n; i++){
if(current <= arr[i].startTime){
current = arr[i].endTime;
count++;
}
}
cout << count << endl;
}
return 0;
}