1 简单贪心
书上代码
/**
算法名称: PAT B1020 月饼
详 情 : 旺仔 2020.04.06
算法想法: 简单贪心 :把收益高的先卖完
**/
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 1010;
struct mooncake{
double store;
double sell;
double price;
}cake[maxn];
bool cmp( mooncake a, mooncake b){
return a.price > b.price ;
}
int main()
{
int n;
double D;
scanf("%d%lf",&n,&D);
for(int i = 0 ; i < n ; i ++){
scanf("%lf",&cake[i].store);
}
for(int i = 0 ;i < n ; i ++){
scanf("%lf",&cake[i].sell);
cake[i].price = cake[i].sell / cake[i].store;
}
sort(cake,cake+n,cmp);
double ans = 0;
for(int i = 0 ; i < n ; i++){
if(cake[i].store <= D){
D = D - cake[i].store;
ans =ans + cake[i].sell;
}else{
ans = ans +cake[i].price*D;
break;
}
}
printf("%.2f\n",ans);
return 0;
}
PAT B1023 组个最小数
/**
算法名称: PAT B1023 组个最小数
详 情 : 旺仔 2020.04.06
算法想法: 除了0 之外的顺序拍
**/
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
int Count[10];
for(int i = 0 ; i < 10; i++){
scanf("%d",&Count[i]);
}
sort(Count,Count+10);
int flaga, flagb;
for(int i = 0 ; i < 10 ; i ++){
if(Count[i] == 0){
flaga = i;
break;
}
}
for(int i = 0 ; i < 10 ; i ++){
if(Count[i] != 0){
flagb = i;
break;
}
}
if(flagb != 0)
{
int temp;
temp = Count[flaga];
Count[flaga] = Count[flagb];
Count[flagb] = temp;
}
for(int i = 0; i < 10; i ++){
cout<<Count[i]<<" ";
}
cout<<endl;
return 0;
}
2 区间贪心
问题:区间不相关
/**
算法名称: 区间不相关问题
详 情 : 旺仔 2020.04.07
问题描述: 给出N个开区间(x,y),从中选择尽可能多的开区间,使得这开区间两两没有交集
算法想法:将其排列后,最左边的区间
**/
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1000;
struct Node{
int x,y;
}point[maxn];
//如果左端点相同 啧按右端点
bool cmp(Node a,Node b){
if(a.x != b.x){
return a.x > b.x;
}else
return a.y <b.y;
}
int main()
{
int n;
cin >> n;
for(int i = 0 ; i < n ; i ++){
cin>>point[i].x >> point[i].y;
}
sort(point,point+n,cmp);
int flag ,ans= 1 ;
flag = point[0].x;
//书上这样写,真的不会漏情况了吗
for(int i = 1 ; i< n ; i ++){
if(point[i].y <= flag){
flag = point[i].x;
ans ++;
}
}
cout<<ans<<endl;
return 0;
}