ACM之动态申请内存

来源:互联网 发布:淘宝虚拟物品出售规则 编辑:程序博客网 时间:2024/05/18 03:51
今天在csuoj上做了一道找3个字符串的最长公共子序列的题,因为要开辟三维数据很费内存,所以用动态开辟再释放内存的方式很好。

1060: Nearest Sequence

Time Limit: 1 Sec  Memory Limit: 64 MB
Submit: 375  Solved: 121
[Submit][Status][Web Board]

Description

        Do you remember the "Nearest Numbers"? Now here comes its brother:"Nearest Sequence".Given three sequences of char,tell me the length of the longest common subsequence of the three sequences.

Input

        There are several test cases.For each test case,the first line gives you the first sequence,the second line gives you the second one and the third line gives you the third one.(the max length of each sequence is 100)

Output

        For each test case,print only one integer :the length of the longest common subsequence of the three sequences.

Sample Input

abcdabdcdbcaabcdcabdtsc

Sample Output

21

以下为代码
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int max1(int a,int b)
{
if(a>b)return a;
else return b;
}
int max2(int a,int b,int c,int d,int e,int f)
{
int max=-1;
if(a>max)
max=a;
if(b>max)
max=b;
if(c>max)
max=c;
if(d>max)
max=d;
if(e>max)
max=e;
if(f>max)
max=f;
return max;
}
int maxlen(char* str1,char* str2,char* str3)
{
int i,j,k,len1,len2,len3,mxlen;
len1=strlen(str1);
len2=strlen(str2);
len3=strlen(str3);
int ***c=new int **[len1+1];//动态申请内存 
for(i=0;i<=len1;i++)
{
c[i]=new int *[len2+1];
for(j=0;j<=len2;j++)
c[i][j]=new int[len3+1];
}
for(i=0;i<=len1;i++)//赋初始值,因为要从后面开始比较,所以当数据下标取到len1,len2,len3时都为0 
for(j=0;j<=len2;j++)
c[i][j][len3]=0;
for(i=0;i<=len1;i++)
for(k=0;k<=len3;k++)
c[i][len2][k]=0;
for(j=0;j<=len2;j++)
for(k=0;k<=len3;k++)
c[len1][j][k]=0;
for(i=len1-1;i>=0;i--)
{
for(j=len2-1;j>=0;j--)
{
for(k=len3-1;k>=0;k--)
{
if(str1[i]==str2[j]&&str2[j]==str3[k])//这里是与2个字符串比较时主要不同的地方,不过也是大同小异 
c[i][j][k]=c[i+1][j+1][k+1]+1;
else if(str1[i]==str2[j]&&str2[j]!=str3[k])
c[i][j][k]=max1(c[i+1][j+1][k],c[i][j][k+1]);
else if(str1[i]!=str2[j]&&str2[j]==str3[k])
c[i][j][k]=max1(c[i][j+1][k+1],c[i+1][j][k]);
else if(str1[i]==str3[k]&&str2[j]!=str3[k])
c[i][j][k]=max1(c[i+1][j][k+1],c[i][j+1][k]);
else //三个都不相同就在上面的6个情况下取最大值 
{
c[i][j][k]=max2(c[i+1][j+1][k],c[i][j][k+1],c[i][j+1][k+1],c[i+1][j][k],c[i+1][j][k+1],c[i][j+1][k]);
}
}
}
}
mxlen=c[0][0][0];//保存下最长公共子序列的数,准备释放内存 
for(i=0;i<=len1;i++)//释放内存 
{
for(j=0;j<=len2;j++)
delete[] c[i][j];
delete[] c[i];
}
delete[] c;
return mxlen;
}
int main()
{
char str1[101],str2[101],str3[101];
int a;
while(scanf("%s%s%s",&str1,&str2,&str3)!=EOF)
{
a=maxlen(str1,str2,str3);
cout<<a<<endl;
}
return 0;
}

0 0
原创粉丝点击