算法课程之实现贪心

1 简单贪心 

PAT B1020 月饼

书上代码

/**
    算法名称: 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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值