无题:要求输出最大公共字串长度和执行次数。将来还要输出,,,最大字串。
输入案例:
7 6
ABCBDAB
BDCABA
4 4
ABCD
ABCD
4 5
ABCD
ACBCC
输出答案:
4
4
3
代码写的很笨,先记着怎么写等用到时在仔细研究吧 。
基本思路就是这个表:
y x |
| A | B | C | B | D | A | B |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
B | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 |
D | 0 | 0 | 1 | 1 | 1 | 2 | 2 | 2 |
C | 0 | 0 | 1 | 2 | 2 | 2 | 2 | 2 |
A | 0 | 1 | 1 | 2 | 2 | 2 | 3 | 3 |
B | 0 | 1 | 2 | 2 | 3 | 3 | 3 | 4 |
A | 0 | 1 | 2 | 2 | 3 | 3 | 4 | 4 |
有斜杠的表示加一的操作。
my answer:
#include<iostream>
#include<cstring>
#include<stdio.h>
#include<string>
#include<cmath>
using namespace std;
int main()
{
int m,n;
while(cin>>m>>n)
{
getchar();
/* char a[]={'0','A','B','C','B','D','A','B'};
char b[]={'0','B','D','C','A','B','A'};*/
char a[100],b[100],t;
int i,j;
for( i=1;i<=m;i++){
cin>>t;
a[i]=t;
}
a[i]='\0';
for( j=1;j<=n;j++){
cin>>t;
b[j]=t;
}
b[j]='\0';
int c[100][100];
int count=0;
for( j=0;j<=n;j++){
for( i=0;i<=m;i++){
count++;
if(i==0||j==0)c[i][j]=0;
else if(a[i]==b[j]){
c[i][j]=c[i-1][j-1]+1;
}
else{
c[i][j]=max(c[i-1][j],c[i][j-1]);
}
if(i==m&&j==n){cout<<c[i][j]<<endl;cout<<count<<endl;}
}
}
}
return 0;
}