C++笔试强训day22

目录

1.添加字符

2.数组变换

3.装箱问题

常规一维优化:


1.添加字符

链接

因为lenA <= lenB <= 50,因此可以无脑暴力解题:

遍历所有符合条件的匹配方法,找出最小的不同的数量,即最大的相同的数量

cpp 复制代码
#include <iostream>
using namespace std;
int main() {
	string A;
	string B;
	cin >> A >> B;
	int c1 = A.size();
	int c2 = B.size();
	int cnt = 0;
	if (c1 == c2)
	{
		for (int i = 0; i < c1; i++)
		{
			if (A[i] != B[i])
				cnt++;
		}
		cout << cnt << endl;
	}
	else
	{
		int dif = c2 - c1;
		int max_n = 0;
		for (int i = 0; i <= dif; ++i)
		{	
			cnt = 0;
			int j = 0;
			int k = i;
			while (j < c1)
			{
				if (A[j] == B[k])
					cnt++;
				j++;
				k++;
			}
			max_n = max(max_n, cnt);
		}
		cout << c1 - max_n << endl;
	}
	return 0;
}

2.数组变换

链接

判断是否为2的n次方就好了。

cpp 复制代码
#include <iostream>
using namespace std;
int arr[60];
int main() {
	int n;
	cin >> n;
	int maxn = 0;
	int x;
	for (int i = 1; i <= n; ++i)
	{
		cin >> x;
		arr[i] = x;
		maxn = max(maxn, x);
	}
	for (int i = 1; i <= n; ++i)
	{
		if (!((maxn / arr[i]) % 2 == 0 || arr[i] == maxn))
		{
			cout << "NO" << endl;
			return 0;
		}
	}
	cout << "YES" << endl;
	return 0;
}

3.装箱问题

链接

01背包dp问题:

讲题意逆向转化为使装入的体积最大更好求解,最后返回时返回V - dp[n][V]即可。

cpp 复制代码
#include <iostream>
using namespace std;

int V, n;
int v[20010];
int dp[40][20010];
int main()
{
	cin >> V >> n;
	for (int i = 1; i <= n; ++i)
		cin >> v[i];
	
	// 填表
	for (int i = 1; i <= n; ++i)
	{
		for (int j = 1; j <= V; ++j)
		{
			dp[i][j] = dp[i - 1][j];
			if (j >= v[i])
				dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - v[i]] + v[i]);
		}
	}
	cout << V - dp[n][V] << endl;
	return 0;
}
常规一维优化:
cpp 复制代码
#include <iostream>
using namespace std;

int V, n;
int v[20010];
int dp[20010];
int main()
{
	cin >> V >> n;
	for (int i = 1; i <= n; ++i)
		cin >> v[i];
	
	// 填表
	for (int i = 1; i <= n; ++i)
		for (int j = V; j >= v[i]; --j)
				dp[j] = max(dp[j], dp[j - v[i]] + v[i]);

	cout << V - dp[V] << endl;
	return 0;
}
相关推荐
励志不掉头发的内向程序员1 分钟前
STL库——string(类函数学习)
开发语言·c++
图灵学术计算机论文辅导20 分钟前
论文推荐|迁移学习+多模态特征融合
论文阅读·人工智能·深度学习·计算机网络·算法·计算机视觉·目标跟踪
threejs源码翻译官1 小时前
显微镜图像处理【优化】- 使用图像风格迁移技术放大图像细节
算法
强德亨上校1 小时前
贪心算法(Greedy Algorithm)详解
算法·贪心算法
浮灯Foden2 小时前
算法-每日一题(DAY13)两数之和
开发语言·数据结构·c++·算法·leetcode·面试·散列表
淡海水3 小时前
【原理】Struct 和 Class 辨析
开发语言·c++·c#·struct·class
西工程小巴3 小时前
实践笔记-VSCode与IDE同步问题解决指南;程序总是进入中断服务程序。
c语言·算法·嵌入式
Tina学编程3 小时前
48Days-Day19 | ISBN号,kotori和迷宫,矩阵最长递增路径
java·算法
Moonbit3 小时前
MoonBit Perals Vol.06: MoonBit 与 LLVM 共舞 (上):编译前端实现
后端·算法·编程语言
青草地溪水旁4 小时前
UML函数原型中stereotype的含义,有啥用?
c++·uml