[Algorithm][综合训练][字符编码][最少的完全平方数][游游的字母串]详细讲解


1.字符编码

1.题目链接


2.算法原理详解 && 代码实现

  • 解法:给一个字符串进行二进制编码,使得编码后的字符串长度最短 --> 哈夫曼编码
    #include <iostream>
    #include <string>
    #include <vector>
    #include<queue>
    using namespace std;
    
    int main()
    {
        string str;
        while(cin >> str)
        {
            // 1.统计每个字符的频次
            int hash[300] = { 0 };
            for(const auto& ch : str)
            {
                hash[ch]++;
            }
    
            // 2.将所有的频次放入堆中
            priority_queue<int, vector<int>, greater<>> heap;
            for(int i = 0; i < 300; i++)
            {
                if(hash[i])
                {
                    heap.push(hash[i]);
                }
            }
    
            // 3.哈夫曼编码
            int ret = 0;
            while(heap.size() > 1)
            {
                int x1 = heap.top();
                heap.pop();
                int x2 = heap.top();
                heap.pop();
    
                ret += x1 + x2;
                heap.push(x1 + x2);
            }
    
            cout << ret << endl;
        }
    
        return 0;
    }
    

2.最少的完全平方数

1.题目链接


2.算法原理详解 && 代码实现

  • 思路:从一些数里面选,每个数都可以选无穷多次,在限定条件下,达到目的
  • 解法:完全背包 -> 空间优化版本
    • 状态表示dp[i][j]:从前i割数中挑选,总和恰好为j时,最少挑出来几个数

    • 状态转移方程
      请添加图片描述

    • 初始化
      请添加图片描述

    • 返回值dp[sqrt(n)][n]

    #include <iostream>
    #include <cstring>
    using namespace std;
    
    const int N = 1e4 + 10;
    
    int main()
    {
    	int n = 0;
    	cin >> n;
    	
    	int dp[N];
    	memset(dp, 0x3f, sizeof dp);
    	dp[0] = 0;
    
    	for(int i = 1; i * i <= n; i++)
    	{
    		for(int j = i * i; j <= n; j++)
    		{
    			dp[j] = min(dp[j], dp[j - i * i] + 1);
    		}
    	}
    
    	cout << dp[n] << endl;
    
    	return 0;
    }
    

3.游游的字母串

1.题目链接


2.算法思路详解 && 代码实现

  • 解法暴力枚举所有可能变成的字符情况

    • 如何求变化次数min(abs(a - z), 26 - abs(a - z))
      请添加图片描述
    #include <iostream>
    #include <cmath>
    #include <string>
    using namespace std;
    
    int main()
    {
        string str;
        cin >> str;
        
        int ret = 0x3f3f3f3f;
        for(char ch = 'a'; ch <= 'z'; ch++) // 枚举变成什么字符
        {
            int sum = 0;
            for(auto x : str)
            {
                sum += min(abs(x - ch), 26 - abs(x - ch));
            }
            ret = min(ret, sum);
        }
        
        cout << ret << endl;
        
        return 0;
    }
    
  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DieSnowK

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值