暴力枚举法

虽然暴力枚举法有时候效率低,时间复杂度高,但是在面对小规模数据集的时候,暴力枚举法往往是很好的思维利器。

B: 01 串的熵(5分)

问题描述

cpp 复制代码
#include <iostream>
#include <cmath>
#include <algorithm>

using namespace std;

const int total = 23333333;
const double H = 11625907.5798;

int main() {
    for (int i = 0; i < total / 2; i++) {
        double ans = 0;
        ans -= 1.0 * i * i / total * log2(1.0 * i / total);//计算0的信息熵 
        ans -= 1.0 * (total - i) * (total - i) / total * log2(1.0 * (total - i) / total);//计算1的信息熵 
        if (abs(ans - H) < 1e-4) {//计算实际值与计算值之间的绝对值 如果在1e-4这个误差之内,则说明计算值正确 
            cout << i << endl;//输出实际0的个数 
            return 0;
        }
    }
    return 0;
}

这道题目的思想很简单,就是第一步计算0的信息熵,接着第二步计算1的信息熵,之后与题目给定的信息熵进行误差对比。最后输出实际01串中0的实际数目

可能大家会觉得这样子计算,会使得计算十分的复杂,这里提供新的思路,就是二分法。

复制代码
#include <iostream>
#include <cmath>
#include <algorithm>

using namespace std;

const int total = 23333333;
const double H = 11625907.5798;

int main() {
    int l = 0, r = total / 2;
    while (l < r) {
        int mid = (l + r) >> 1;
        double ans = 0;
        ans -= 1.0 * mid * mid / total * log2(1.0 * mid / total);
        ans -= 1.0 * (total - mid) * (total - mid) / total * log2(1.0 * (total - mid) / total);
        if (abs(ans - H) < 1e-4) {
            cout << mid << endl;
            return 0;
        }
        if (ans > H) {
            r = mid;//这里我的理解是,整个信息熵的计算过程是一个递增函数,所以 当计算结果大了,我们就应该将函数的因变量i 也就是0的个数进行相应的缩减 
        } else {
            l = mid + 1;//反之亦然 当计算结果小了 则相应的提高0的出现次数 
        }
    }
    return 0;
}
相关推荐
Jerry13 小时前
LeetCode 28. 找出字符串中第一个匹配项的下标
算法
Jerry15 小时前
LeetCode 459. 重复的子字符串
算法
海石17 小时前
1500分的题目,确实有实力,不过还是我略胜一筹
算法·leetcode
海石17 小时前
【记忆化搜索】条条大路通AC,走好适合你的那一条,走到后再考虑走得快
算法·leetcode
Jerry19 小时前
LeetCode 151. 反转字符串中的单词
算法
a1117761 天前
LM 算法迭代过程动画演示(SLAM)
算法
头茬韭菜1 天前
Context 的生死抉择:四层压缩、截断算法与 Session Memory
算法·ai
Jerry1 天前
LeetCode 541. 反转字符串 II
算法
Jerry1 天前
LeetCode 344. 反转字符串
算法
搞科研的小刘选手1 天前
【香港大学主办&IEEE出版】第六届计算机视觉、应用与算法国际学术会议(CVAA 2026)
算法·计算机视觉·应用·学术会议