博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
最长公共子序列
阅读量:3947 次
发布时间:2019-05-24

本文共 1541 字,大约阅读时间需要 5 分钟。

最长公共子序列

Time Limit: 1000 ms Memory Limit: 32768 KiB

 

Problem Description

从一个给定的串中删去(不一定连续地删去)0个或0个以上的字符,剩下地字符按原来顺序组成的串。例如:“ ”,“a”,“xb”,“aaa”,“bbb”,“xabb”,“xaaabbb”都是串“xaaabbb”的子序列。(例子中的串不包含引号。)

 
编程求N个非空串的最长公共子序列的长度。限制:2<=N<=100;N个串中的字符只会是数字0,1,…,9或小写英文字母a,b,…,z;每个串非空且最多含100个字符;N个串的长度的乘积不会超过30000。

Input

文件第1行是一个整数T,表示测试数据的个数(1<=T<=10)。接下来有T组测试数据。各组测试数据的第1行是一个整数Ni,表示第i组数据中串的个数。各组测试数据的第2到N+1行中,每行一个串,串中不会有空格,但行首和行末可能有空格,这些空格当然不算作串的一部分。

Output

输出T行,每行一个数,第i行的数表示第i组测试数据中Ni个非空串的最长公共子序列的长度。

Sample Input

13abbccd

Sample Output

0

 

代码如下:

#include 
#include
#include
int max2(int a,int b){ if(a>b) return a; else return b;}int min2(int a,int b){ if(a
=1;i--) index=index*len[i]+x[i]-1; //记忆化搜索 if(dp[index]>=0) return dp[index]; //判断是否所有串的最后一个字符都相等 for(i=2;i<=n;i++) if(s[1][x[1]-1]!=s[i][x[i]-1]) break; if(i>n) //如果都相等,则最大长度+1 { for(j=1;j<=n;j++) x[j]--; ret=LCS(x)+1; for(j=1;j<=n;j++) x[j]++; } else //否则,求删去某个字符串的最后一个字符之后得到的最大值 { ret=0; for(j=1;j<=n;j++) { x[j]--; int t=LCS(x); ret=max2(t,ret); x[j]++; } } dp[index]=ret; return ret;}int main(){ int t,i; int temp[105]; scanf("%d",&t); while(t--) { scanf("%d",&n); for(i=1;i<=n;i++) { scanf("%s",s[i]); len[i]=temp[i]=strlen(s[i]); } memset(dp,-1,sizeof(dp)); printf("%d\n",LCS(temp)); } return 0;}

 

转载地址:http://ikhwi.baihongyu.com/

你可能感兴趣的文章
Parsing XML Data
查看>>
Optimizing Downloads for Efficient Network Access
查看>>
Minimizing the Effect of Regular Updates
查看>>
Redundant Downloads are Redundant
查看>>
Modifying your Download Patterns Based on the Connectivity Type
查看>>
Supporting Different Screen Sizes支持不同的屏幕尺寸
查看>>
Supporting Different Densities 支持各种屏幕密度
查看>>
Implementing Adaptative UI Flows 实施自适应用户界面流程
查看>>
Crossfading Two Views 淡入淡出的两种观点
查看>>
Using ViewPager for Screen Slides 使用屏幕幻灯片ViewPager
查看>>
Displaying Card Flip Animations 显示卡片翻转动画
查看>>
Zooming a View 缩放视图
查看>>
Animating Layout Changes 动画布局的更改
查看>>
Controlling Your App’s Volume and Playback 控制应用程序的音量和播放
查看>>
Managing Audio Focus 管理音频焦点
查看>>
Dealing with Audio Output Hardware 处理音频输出硬件设备
查看>>
Monitoring the Battery Level and Charging State 监测电池电量和充电状态
查看>>
Determining and Monitoring the Docking State and Type 判断并监测设备的停驻状态与类型
查看>>
Determining and Monitoring the Connectivity Status 根据网络连接状况去省电
查看>>
Manipulating Broadcast Receivers On Demand 按需操控广播接收
查看>>