动态规划——Poj 1159 Palindrome

红米K70至尊版修复“nv损坏”主板电阻图示 mtk芯片工程固件刷写与步骤说明 💝💝💝红米K70至尊版 机型代码:rothko,搭载天玑9300+旗舰芯片.后置5000万像素索尼IMX906高动态OIS主摄,800万像素超广角镜头,200万像素微距镜头,前置2000万像素摄像头,也适用于以下型号的小米机型:2407FPN8EG,2407FPN8ER,XIG06,A402XM,2407FRK8EC。 💝💝💝通过博文了解 1💝💝💝-----此机型工程固件的资源刷写注意事项 2💝💝💝-----此机型刷写工程固件预览界面 3💝💝💝------红米K 阅读详情

1)   题目

Palindrome

Time Limit: 3000MS

 

Memory Limit: 65536K

Total Submissions: 46005

 

Accepted: 15688

Description

A palindrome is a symmetrical string, that is, a string read identically from left to right as well as from right to left. You are to write a program which, given a string, determines the minimal number of characters to be inserted into the string in order to obtain a palindrome. 

As an example, by inserting 2 characters, the string "Ab3bd" can be transformed into a palindrome ("dAb3bAd" or "Adb3bdA"). However, inserting fewer than 2 characters does not produce a palindrome. 

Input

Your program is to read from standard input. The first line contains one integer: the length of the input string N, 3 <= N <= 5000. The second line contains one string with length N. The string is formed from uppercase letters from 'A' to 'Z', lowercase letters from 'a' to 'z' and digits from '0' to '9'. Uppercase and lowercase letters are to be considered distinct.

Output

Your program is to write to standard output. The first line contains one integer, which is the desired minimal number.

Sample Input

5

Ab3bd

Sample Output

2


2)    题意

题目给出回文的定义:一串字符,从左往右读和从右往左读是完全一样的。比如aba,从左往右读和从右往左读都是aba。

给出一串字符,求使该字符串是回文需要添加的最少字符个数。


3)    数据范围

字符串的长度n,3<=n<=5000。


4)    算法

动态规划法。设字符串为S,长度为L,d[i][j]表示以第i个字符为首,第j个字符为尾的字符串构成回文最少需要添加的字符个数,i和j的初值分别为1、L。

如果S[i] == S[j],即字符串两端的字符相等,d[i][j] = d[i+1][j-1],

即d[i][j]等于去掉头尾后的字符串的d值。

如果S[i] != S[j],此时划分出两个子问题,求d[i][j-1]和d[i+1][j],它两中较小的值再加1即为d[i][j](加上的1个字符是用于和S[i]或者S[j]构成对称的)。

状态转移方程:


从上面的分析可以看出,这个问题的实质是求最长公共子序列,只是这两个序列分别是串S的前一部分和串S后一部分的逆序列。


5)    代码

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

#define MIN(a, b) ((a) < (b) ? (a) : (b))

#define MAXSIZE 5005

//开始没有考虑内存问题,使用了int型,超内存限制,也可使用滚动数组解决
unsigned short d[MAXSIZE][MAXSIZE];

int ToPalindrome(char *s, int n)
{
	int i, j, k;
	//只有一个字符时,不需要添加字符
	for (i = 0; i < n; i++)
	{
		d[i][i] = 0;
	}
	//串长度为2时
	for (i = 1; i < n; i++)
	{
		if (s[i-1] == s[i])
		{
			d[i-1][i] = 0;
		}
		else
		{
			d[i-1][i] = 1;
		}
	}

	//串长度递增
	for (k = 2; k < n; k++)
	{
		for (i = 0, j = k; j < n; i++, j++)
		{
			if (s[i] == s[j])
			{
				d[i][j] = d[i+1][j-1];
			}
			else
			{
				d[i][j] = MIN(d[i][j-1], d[i+1][j]) + 1;
			}
		}
	}
	return d[0][n-1];
}

int main(void)
{
	char str[MAXSIZE];

	int n;
	while (scanf("%d", &n) != EOF)
	{
		getchar();
		gets(str);
		printf("%d\n", ToPalindrome(str, n));
	}
	return 0;
}

6)    测试数据

5

Ab3bd

3

aaa

7

Aabcdba

7)    提交结果


【网络与爬虫 62】小程序爬虫终极攻略:微信支付宝小程序数据采集完全指南 本文深入解析微信和支付宝小程序的爬虫技术,从基础架构分析到高级逆向工程,涵盖WXML/AXML模板解析、API接口拦截、网络流量分析等核心技术。通过实战案例和代码示例,帮助开发者掌握小程序数据采集的完整技术栈。 阅读详情

相关推荐

华为云Stack应急预案实战:从IaaS到PaaS的故障场景与恢复指南

本文详细解析华为云Stack应急预案在IaaS到PaaS层的故障场景与恢复实践,涵盖计算节点故障、存储链路中断等典型问题。通过标准化操作流程和实战案例,帮助企业在突发故障时快速恢复业务,确保高可用性。华为云Stack的应急预案体系经过金融、政务等严苛场景验证,恢复时间指标(RTO)控制在30分钟以内。

weixin_33724059的博客 378

(POJ) 1159 Palindrome

传送门 题目大意:给你一串字符串,问最少添加几个字符可以使该字符串变成回文串。 解题思路:先求出该字符串的最长回文子串。然后总长度减去最长回文子串的长度就行了。已经形成回文的我们没有必要多此一举去添加字符了,而还单着的,我们在相对的位置在给他加一个就行了。 但是直接区间dp求最长回文字串,开二维数组会MLE,而又不太好滚动(不知道可不可以滚动),不过可以直接开short 莽过。 #inc...

一只不争气的蒸汽机的博客 288

手把手教你用SlowFast训练自定义手势识别数据集(附FFmpeg抽帧技巧)

本文提供了一份基于SlowFast架构训练自定义手势识别数据集的完整实战指南。文章重点剖析了数据准备的核心挑战,详细讲解了利用FFmpeg进行高、低帧率抽帧的技巧,并介绍了构建半自动标注流水线、生成符合SlowFast要求的AVA格式数据集文件的具体方法。最后,针对手势识别场景,给出了关键的模型训练配置与调优建议,帮助开发者高效完成从数据到模型的全流程。

s1t2u3的博客 915

poj1159--Palindrome(dp:最长公共子序列变形 + 滚动数组)

Palindrome Time Limit: 3000MS   Memory Limit: 65536K Total Submissions: 53414   Accepted: 18449 Description A palindrome is a symmetrical string, that is, a string read ide

随风的专栏 1137

QMI8658A和QMC5883L传感器校准全攻略:从零偏校准到椭球拟合

本文详细解析了QMI8658A和QMC5883L传感器的校准方法,从零偏校准到椭球拟合,涵盖了9轴运动传感器的核心误差来源及补偿技术。通过实战案例和数学建模,帮助开发者提升传感器精度,适用于无人机、AR/VR等智能硬件应用。

weixin_29189381的博客 165

2026年全球VCSEL芯片竞争格局揭秘:美欧亚“三足鼎立”,中国军团强势崛起

全球VCSEL芯片市场迎来爆发期,预计2032年规模将达110亿元。美国Lumentum、Coherent等巨头主导消费电子和光通信领域,欧洲ams-OSRAM、TRUMPF则在车规级高功率VCSEL占据优势。中国企业如长光华芯、纵慧芯光加速追赶,实现从3D传感向激光雷达的技术跨越。行业未来聚焦高功率、多结阵列化发展,自动驾驶和AI算力需求将推动市场持续增长,但面临技术壁垒、供应链依赖等挑战。国际巨头与中国厂商将在这一光芯片赛道展开激烈竞争。

致力于lidar应用开发 791

【POJ1159】Palindrome(动态规划)

题面:【POJ1159】Palindrome 这道题是一道较水的DP题。 我们可以用f[i][j]来表示把[i..j]这个区间变成一个回文串所需添加的最少字母数,这样我们就可以轻松地得到状态转移方程: 当s[i]==s[j]时,f[i][j]=min{f[i+1][j-1],f[i+1][j]+1,f[i][j-1]+1};当s[i]!=s[j]时,f[i][j]=min{f[i+1][j]...

CXR的博客 894

Prompt进阶2:LangGPT(构建高性能Prompt策略和技巧)--最佳实践指南

Prompt进阶2:LangGPT(构建高性能Prompt策略和技巧)--最佳实践指南

丨汀、的博客 2656

POJ--1159:Palindrome (DP求最长公共子序列)

1. 题目源地址:http://poj.org/problem?id=1159 2. 题目大意:

酒酿小圆子呀~ 701

TC3XX - MCAL知识点(三十五):Tasking编译器下,Tc3xx的MCAL代码如何使用多核,多核中断、多核任务、多核外设之间的MCAL配置与代码例程

文章用于记录在裸机情况下使用多核Tc387芯片,如何高效运行以及正确的代码、工程属性、链接文件配置等问题,相互结合、相互影响的地方,以示后续使用记录。

梦想技术家 969

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

poj-1159-Palindrome

PalindromeTime Limit: 3000MS Memory Limit: 65536K Total Submissions: 62538 Accepted: 21797DescriptionA palindrome is a symmetrical string, that is, a string read identically from left to r

大桶爆米花eee 261

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

【动态规划】【poj 1159】palindrome

【动态规划】【poj 1159】palindrome 问题 给定一个长度为n( 分析 设原序列S的逆序列为S',则这道题目的关键在于, 最少需要补充的字母数= 原序列S的长度— S和S'的最长公共子串长度 设 S 为原字符串,RS=reverse(S)即S反转后的字符串,LCS(S,RS)为S与RS的最长公共子序列,len(S)为S的长度。令S={a1~an},则RS={a

pi9nc的专栏 944

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

POJ 1159 Palindrome [动态规划+滚动数组]

POJ 1195 Palindrome [动态规划+滚动数组] 写在最前面:吹爆滚动数组!!!!!!!太好用了叭!!!快学它!!! 题目:http://poj.org/problem?id=1159 题目大意:求最少增加几个字符可以使字符串s变成回文串 样例: 输入:5 Ab3bd 输出:2 思路:动态规划 设置状态:f[i][j]的值表示从s[i]到s[j]至少增加几个字符可以使s[i…j]变成...

MMMMMelody的博客 333

POJ1159 Palindrome 【动态规划】

Palindrome Time Limit: 3000MS   Memory Limit: 65536K Total Submissions: 52571   Accepted: 18124 Description A palindrome is a symmetrical string, that is, a string read

长风的专栏 1232

Palindrome(poj1159)(动态规划)

Palindrome Time Limit: 3000MS   Memory Limit: 65536K Total Submissions: 53877   Accepted: 18610 Description A palindrome is a symmetrical string, that is, a string read i

My Castle 897

poj1159 Palindrome

poj1159 Palindrome Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 68871 Accepted: 23964 Description A palindrome is a symmetrical string, that is, a string read identically from left to ...

miracle from life 438

poj 1159 Palindrome 动态规划

lstar@ubuntu:~/ds/poj$ ./a.out 2 lstar@ubuntu:~/ds/poj$ cat 1159_2.in.dat  4 Ab3A Ab33A这种对奇数的情况也需要特殊考虑,如果以中间的3为分界,则返回2,其实最小应该是1 3L7YWY  最短匹配 3L7YWY7L3 只需要3个,且并不是以原中心点为7 Y W进行扩展的,所以自己推断的状

小留家心的爱心之窝 ^_^ 925

POJ 1159 Palindrome (动态规划)

Palindrome Time Limit: 3000MS   Memory Limit: 65536K Total Submissions: 48269   Accepted: 16570 Description A palindrome is a symmetrical string, that is, a string read ide

Hadis_yuki 1516

Palindrome POJ 1159 动态规划

Description A palindrome is a symmetrical string, that is, a string read identically from left to right as well as from right to left. You are to write a program which, given a string, determines t

JWMNEU的专栏 776

POJ 1159 Palindrome(动态规划:最长回文子序列)

//POJ 1159 Palindrome(动态规划:最长回文子序列) #include #include #include #include #include using namespace std; int dp[2][5050]; int Max(int a,int b) { if(a>b) { return a; } return b; }

u014068781的专栏 538

POJ1159 Palindrome(动态规划问题)

题目:DescriptionA palindrome is a symmetrical string, thatis, a string read identically from left to right as well as from right to left.You are to write a program which, given a string, determines the ...

qq_40259739的博客 498

POJ 1159 Palindrome(动态规划经典问题)

题意:给出一个长为N的字符串,问最少插入多少字符使的原串成为一个回文串。 分析:动态规划经典问题。从右向左从小到大枚举所有子串计算各dp[i][j]的值。 状态转移方程:str[i]==str[j]:dp[i][j]=dp[i+1][j-1]; (dp[i][j]代表字符串中从i到j位置最少要插入多少字符使得原串成为回文)                          str[i]!=s

iCpC之旅 1033
上一篇: 动态规划——最长上升子序列
下一篇: 递归——Ny 305 表达式求值
庞老板
博客等级 码龄15年 127粉丝 66原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

打赏作者

庞老板

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

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

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

打赏作者

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

抵扣说明:

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

余额充值