惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
B
Blog
Stack Overflow Blog
Stack Overflow Blog
量子位
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Tailwind CSS Blog
MongoDB | Blog
MongoDB | Blog
小众软件
小众软件
博客园 - 三生石上(FineUI控件)
Recent Announcements
Recent Announcements
U
Unit 42
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
腾讯CDC
D
DataBreaches.Net
Microsoft Azure Blog
Microsoft Azure Blog
G
Google Developers Blog
M
MIT News - Artificial intelligence
P
Proofpoint News Feed
罗磊的独立博客
L
LangChain Blog
V
Visual Studio Blog
雷峰网
雷峰网
aimingoo的专栏
aimingoo的专栏
宝玉的分享
宝玉的分享

静静的小窝

在VPS服务器上面安装OpenClaw并使用OpenRouter的免费API的一些“坑” | Some "pits" about installing OpenClaw and using OpenRouter's free API on a VPS server 五年了啊 | Five years 一个奇怪的估算 | A strange estimation 虚拟直播之路2 | Living as a V 2 虚拟直播之路 | Living as a V AI 写代码?| AI coding? X静评1.1:谷歌,快成了?| XComment1.1 Is Google's Success Coming? X静评0.3:要精致吗?| XComment0.3 Be Dainty? X静评0.2:座位是购买的服务还是赠送的服务?| Xcomment0.2 A Bought Seat or A Gift Seat X静评0.1:一纸限令,毁掉一个政策?| XComment0.1 One Paper, One Dead Policy? hadoop 3.2.2 Cluster Setup | hadoop 3.2.2 的集群启动 VY223 Journal Smith’s death 第一次翻墙|first cross wall [题解]异或三角形|2021蓝桥杯国赛|xor triangle 2021年蓝桥杯|LanQiaoCup2021 参赛|Attending Contest 新旧|New and Old 去毛泽东旧居| visit MAO ZEDONG old house 拜登会团结美国吗|Will Biden unite the USA? 出生|Birth 背包问题|knapsack problem 冒泡排序与排序的稳定性|Bubble Sort and Stability 看完哔哩哔哩上的NASA的火星车直播后的一些话|My words after watching NASA's launch of the Mars 2020 perseverance rover live on Bilibili 选择排序|Selection Sort 饭圈与特郎普|fandom and Trump 不盲目|No Blindness 从3到n——一道数学题|a math problem from 3 to N 公权与私权|public and private rights 我在第几层|Where I Am
894A题解|894A Solution
静静 · 2023-01-15 · via 静静的小窝

这是之前出的一道题,稍微进行了一些小修改。
题目链接:https://codeforces.com/contest/894/problem/A

  1. 最简单的方法就是搜索遍历所有的可能的排列情况,即枚举结果字符串的每一位在原字符串中的位置,故复杂度为$O(n^3)$,如果需要的匹配的字符串更长,那么复杂度更高。

  2. 随后可以发现目标字符串要完全符合要求,意即只要有一位不符合就一定不被计算,故可剪枝,只有当前面的字符串都符合要求的时候才继续遍历,常数可以进行优化为原来的$\frac{1}{26}$,但复杂度仍旧不变。

  3. 从前面的剪枝可以发现并不一定要遍历每种可能才可以,可以保存中间量直接相加即动态规划

可以一维存储原字符串的下标,一维存目标字符串的下标,表示到目前为止符合的字符串数量,随后从前往后相加得最后得数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
for (int j = 0; j < 105; j++)
{
for (int i = 1; i < 5; i++)
{
dp[i][j] = 0;
}
dp[0][j]=1;
}
for (int j = 0; j < st.length(); j++)
{
for (int i = 0; i < 3; i++)
{
if (st[j] == base[i])
{
dp[i + 1][j + 1] = dp[i][j] + dp[i+1][j];
}
else
{
dp[i + 1][j + 1] = dp[i + 1][j];
}
}

最后输出dp[3][st.length()]作为答案。

可以注意到过程当中一直是dp[i]dp[i+1],说明实际并不需要这一维度,可以删去这一维度到

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
for (int i = 1; i < 5; i++)
{
dp[i] = 0;
}
dp[0] = 1;
for (int j = 0; j < st.length(); j++)
{
for (int i = 0; i < 3; i++)
{
if (st[j] == base[i])
{
dp[i + 1] = dp[i] + dp[i + 1];
}
else
{
dp[i + 1] = dp[i + 1];
}
}
}

同时注意到else实际上什么都没有做,可以直接删去。