贪心(总结+例题)

贪心是什么?

定义:

所谓贪心算法是指,在对问题求解时,总是做出在当前看来是最好的选择。 也就是说,不从整体最优上加以考虑,他所做出的仅是在某种意义上的局部最优解。

注意

贪心算法不是对所有问题都能得到整体最优解,关键是贪心策略的选择

算法思路

贪心算法一般按如下步骤进行:

  1. 建立数学模型来描述问题
  2. 把求解的问题分成若干个子问题
  3. 对每个子问题求解,得到子问题的局部最优解
  4. 把子问题的解局部最优解合成原来解问题的一个解

使用条件

  1. 贪心选择性质

一个问题的整体最优解可通过一系列局部的最优解的选择达到,并且每次的选择可以依赖以前作出的选择,但不依赖于后面要作出的选择。这就是贪心选择性质。对于一个具体问题,要确定它是否具有贪心选择性质,必须证明每一步所作的贪心选择最终导致问题的整体最优解

  1. 最优子结构性质

当一个问题的最优解包含其子问题的最优解时称此问题具有最优子结构性质。问题的最优子结构性质是该问题可用贪心法求解的关键所在。在实际应用中,至于什么问题具有什么样的贪心选择性质是不确定的,需要具体问题具体分析

存在问题

  1. 不能保证解是最佳的。因为贪心算法总是从局部出发,并没从整体考虑
  2. 贪心算法一般用来解决求最大或最小解
  3. 贪心算法只能确定某些问题的可行性范围

例题

1
I love string 我爱弦乐

Problem Description

Mr X likes to play string games.
Mr X has an operation sequence. This operation sequence can be written
as a string. For each operation, the next character of the operation
sequence can be inserted before or after the current string. For
example, my operation sequence is “aabac”, suppose the sequence
obtained after the first four operations is “baaa”, then after the
last operation, the string may become “baaac” or “cbaaa”. It can be
seen that there is only one operation method for the first operation.
For other operations, there are only two methods of operation.

For each operation method, there will be a score. The smaller the
lexicographic order of the final string, the higher the final score.

Then, for a given operation sequence, how many operation methods can
get the maximum score.

The two operation methods are different. If and only if there is a
certain operation (not the first operation), one operation will be
inserted before the current string, and the other operation will be
inserted after the current string.

Input

Enter a positive integer T (T≤10) on the first line to represent the number of test cases.
For each test case:

the first line contains a integer n (1≤n≤100000) to represent the
length of the string.

the second line contains a string of lowercase letters , which
represents the sequence of operations.

Output

For each test case, output a line of a positive integer to represent
the number of schemes, and the answer is modulo 1000000007

Sample Input

1
5
abcde

Sample Output

1

思路:
字典序小的放后面,大的放前面~
相同就乘2

#include <iostream>
using namespace std;
const int N = 1e5 + 10, mod = 1e9 + 7;;

int main()
{
    int T;
    cin >> T;
    while (T--)
    {
        int n;
        string str;
        cin >> n >> str;
        
        long long ans = 1;
        char l = str[0], r = str[0];
        for (int i = 1; i < n; i++)
        {
            if (str[i] == l && str[i] == r) ans = ans * 2 % mod;
            else if (str[i] <= l) l = str[i];  
            else r = str[i];
        }
        
        cout << ans % mod << endl;
    }
    return 0;
}

2
区间选点 传送门

给定 N 个闭区间 [ai,bi],请你在数轴上选择尽量少的点,使得每个区间内至少包含一个选出的点。

输出选择的点的最小数量。

位于区间端点上的点也算作区间内。

输入格式

第一行包含整数 N,表示区间数。

接下来 N 行,每行包含两个整数 ai,bi,表示一个区间的两个端点。

输出格式

输出一个整数,表示所需的点的最小数量。

数据范围

1≤N≤105
−109≤ai≤bi≤109

输入样例:

3
-1 1
2 4
3 5

输出样例:

2

在这里插入图片描述
将每个区间按照右端点从小到大进行排序(贪心的常规操作)
从前往后枚举区间,end值初始化为无穷小

  • 如果本次区间不能覆盖掉上次区间的右端点, ed < range[i].l

    说明需要选择一个新的点, res ++ ; ed = range[i].r;

证明:

  1. 找到cnt个点,满足题意情况,则最优解Ans <= cnt
  2. 找到cnt个点,即找到cnt个区间,且区间从左到右依次排好,且没有相同的交集,则说明可能有区间没有被这cnt个点覆盖过,所以最优解Ans>= cnt ,则Ans == cnt

证毕。

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 100010;

int n;
struct Range
{
    int l, r;
    bool operator< (const Range &W)const
    {
        return r < W.r;
    }
}range[N];

int main()
{
    scanf("%d", &n);
    
    for (int i = 0; i < n; i ++ ) 
        scanf("%d%d", &range[i].l, &range[i].r);

    sort(range, range + n);

    int res = 0, ed = -2e9;
    for (int i = 0; i < n; i ++ )
        if (range[i].l > ed)
        {
            res ++ ;
            ed = range[i].r;
        }

    printf("%d\n", res);

    return 0;
}

再来个娱乐题

货仓选址

在一条数轴上有 N 家商店,它们的坐标分别为 A1∼AN。

现在需要在数轴上建立一家货仓,每天清晨,从货仓到每家商店都要运送一车商品。

为了提高效率,求把货仓建在何处,可以使得货仓到每家商店的距离之和最小。

输入格式

第一行输入整数 N。

第二行 N 个整数 A1∼AN。

输出格式

输出一个整数,表示距离之和的最小值。

数据范围

1≤N≤100000, 0≤Ai≤40000

输入样例:

4 6 2 9 1

输出样例:

12

只要排序找中点即可
设仓库位置为k
答案为 ans = min{ | X1 - k | + | X2 - k | + | X3 - k |+…+ | Xn - k | }

证明:
这道题目中,每一个点到中位数的距离,都是满足全局的最有性,而不是局部最优性。
设在仓库建在 X 轴坐标处,X 左侧的商店有 P 家 ,右侧的商店有 Q 家
若 P < Q ,则每把仓库的选址向右移动 1 单位距离,距离之和就会变小 Q - P。
同理,若 P > Q , 则仓库的选址向左移动 1 单位距离,距离之和就会变小。
P = Q 时为最优解。

#include <iostream>
#include <algorithm>
using namespace std;
const int N = 100010;
int a[N];
int main()
{
    int n;
    cin >> n;
    for(int i = 0;i < n;i ++) cin >> a[i];
    sort( a , a + n );
    int res = 0;
    for(int i = 0;i < n;i ++) res + = abs( a[i] - a[n/2] );
    cout << res;
    return 0;
}

欢迎点赞与评论~
记得收藏

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
贪心算法和动态规划都是常用于解决问题的算法思想。贪心算法是一种在每一步都做出局部最优决策的算法,而不考虑全局的状态。贪心算法通常具有较低的时间复杂度,因为它不需要回溯所有子问题的解。相比之下,动态规划需要回溯所有子问题的解,因此时间复杂度较高。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [ES6的JavaScript算法思想实现之分而治之,动态规划,贪心算法和回溯算法 贪心算法和动态规划.pdf](https://download.csdn.net/download/qq_40464803/85095551)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [动态规划与贪心算法的区别](https://blog.csdn.net/m0_57236802/article/details/129539553)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [js贪心算法](https://blog.csdn.net/qq_48315043/article/details/121678537)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值