觉得还是先从简单例子程序着手,先了解各个算法的基本思想。

目录:

  1. 贪心算法
  2. 分治法
  3. 动态规划
  4. 回溯法
  5. 分支限界法
  6. 线性规划网络流

算法是指对特定问题求解步骤 的一种描述

算法的评价标准:时间复杂度与空间复杂度。

时间复杂度:考虑给定的数据数目n,关于算法的执行次数。渐进上界用O()表示,最坏情况对衡量算法的好坏具有实际的意义。

空间复杂度:算法占用的空间大小。一般将算法的辅助空间作为衡量标准。

1.贪心算法

算法思想:一个贪心算法总是做出当前最好的选择,也就是说,它期望通过局部最优选择从而得到全局最优的解决方案

小插曲:c++中有排序函数sort,可以直接利用

#include<iostream>
using namespace std;
#include<algorithm>

int main()
{
    int a[4] = { 4,7,3,5 };
    for (int i = 0; i < 4; i++)
        cout << a[i] << " ";
    cout << endl << "排序后::::" << endl;
    sort(a, a + 3);          //可以只对某几项进行排列
    for (int i = 0; i < 4; i++)
        cout << a[i] << " ";


    cin.ignore();
    return 0;
}

4 7 3 5
排序后::::
3 4 7 5

 

 

举列1:最优装载问题

描述:海盗们截获一批财宝,海盗船载重有限,如何尽可能多的获取宝贝??

算法设计:每次选择重量最小的,直到不能再装为止。

代码

#include<iostream>
using namespace std;
#include<algorithm>

const int N = 100;
double w[N];   //古董 的重量数组

int main()
{
    double c;
    int n;
    cout << "请输入载重量c以及古董个数n:" << endl;
    cin >> c >> n;

    cout << "请输入每个古董的重量" << endl;

    for (int i = 0; i < n; i++)
    {
        cin >> w[i];
    }
    sort(w, w + n);

    double temp = 0;
    int ans = 0;

    for (int i = 0; i < n; i++)
    {
        temp += w[i];
        if (temp <= c)
            ans++;
        else
            break;
    }
    cout << "最大装载数目:" << ans << endl;

    cin.ignore();
    cin.ignore();
    cin.ignore();
    return 0;
}
View Code

相关文章:

  • 2022-01-09
  • 2021-08-31
  • 2022-12-23
  • 2021-08-13
  • 2021-06-30
  • 2021-07-18
  • 2022-01-06
猜你喜欢
  • 2021-12-10
  • 2022-12-23
  • 2021-11-10
  • 2021-11-20
  • 2021-12-11
  • 2021-05-21
  • 2022-12-23
相关资源
相似解决方案