【今日三题】小易的升级之路(模拟+gcd) / 礼物的最大价值(动态规划) / 对称之美(字符串哈希)
小易的升级之路(模拟+gcd)
- 小易的升级之路
代码语言:javascript代码运行次数:0运行复制主要考察最大公约数的求法。
#include <iostream>
using namespace std;
int gcd(int a, int b)
{
return b == 0 ? a : gcd(b, a % b);
}
int main()
{
int n, a;
while (cin >> n >> a)
{
while (n--)
{
int b;
cin >> b;
if (a >= b) a += b;
else a += gcd(a, b);
}
cout << a << endl;
}
return 0;
}
礼物的最大价值(动态规划)
- 礼物的最大价值
代码语言:javascript代码运行次数:0运行复制经典路径dp问题。多加一行多加一列后需要注意下标正确映射。
class Solution {
public:
int maxValue(vector<vector<int> >& grid) {
int m = grid.size(), n = grid[0].size();
vector<vector<int>> dp(m + 1, vector<int>(n + 1));
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) + grid[i - 1][j - 1];
return dp[m][n];
}
};
对称之美(字符串哈希)
- 对称之美
代码语言:javascript代码运行次数:0运行复制将所有字符串读入字符串数组中,根据回文串的特点使用双指针遍历从两头向中间遍历,在遍历的过程中如果两边的字符串中没有相同的字符,则不会构成回文串。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
vector<string> vs(n);
for (int i = 0; i < n; i++) cin >> vs[i];
int l = 0, r = n - 1;
for (; l < r; l++, r--)
{
int hash[26] = {};
int flag = 0;
for (auto ch : vs[l]) hash[ch - 'a']++;
for (auto ch : vs[r])
{
if (hash[ch - 'a'])
{
flag = 1;
break;
}
}
if (!flag)
{
cout << "No" << endl;
break;
}
}
if (l >= r) cout << "Yes" << endl;
}
return 0;
}
本篇文章的分享就到这里了,如果您觉得在本文有所收获,还请留下您的三连支持哦~
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。 原始发表:2025-04-13,如有侵权请联系 cloudcommunity@tencent 删除遍历动态规划指针字符串int
发布评论