c语言,为什么没有输出(输出最长公共子序列)
#include<stdio.h>
int main(){
int a,b;
void LCS(int m,int n);
printf("Enter two numbers of the length of strings: \n");
scanf("%d %d",&a,&b);
LCS(a,b);
system("pause");
return 0;
}
void LCS(int m,int n){
int c[m][n];
char x[m+1],y[n+1];
int i,j;
for(i=1;i<=m;i++)
{c[i][0]=0; }
for(j=1;j<=n;j++)
{c[0][i]=0; }
scanf("%s%s",x,y);
for(i=1;i<=m;i++){
for(j=1;j<=n;j++)
{
if(x[i]==y[j])
c[i][j]=c[i-1][j-1]+1;
else
if(c[i-1][j]>=c[i][j-1])
c[i][j]=c[i-1][j];
else
c[i][j]=c[i][j-1];
}
}
i=i+1;j=j+1;
while(i!=0&&j!=0){
if(c[i][j]==c[i-1][j-1]+1)
printf("%c",x[i]);
else
if(c[i][j]==c[i-1][j])
i=i-1;
else
j=j-1;
}
return;
}
[解决办法]
- C/C++ code
#include<stdio.h>void LCS(int m,int n);int main(){ int a,b; printf("Enter two numbers of the length of strings: \n"); scanf("%d %d",&a,&b); LCS(a,b); return 0;}void LCS(int m,int n){ int c[100][100]; //数组长度只能用常量定义 char x[100],y[100]; int i,j; for(i=0;i<=m;i++) //应该把c[0][0]赋值为0 {c[i][0]=0; } for(j=1;j<=n;j++) {c[0][j]=0; } //这里你写错了 scanf("%s%s",x,y); for(i=1;i<=m;i++) { for(j=1;j<=n;j++) { if(x[i - 1]==y[j - 1]) // 数组都是以0下标开始的,所以要i-1 与 j-1 c[i][j]=c[i-1][j-1]+1; else if(c[i-1][j]>=c[i][j-1]) c[i][j]=c[i-1][j]; else c[i][j]=c[i][j-1]; } } i=m;j=n; // i = m; j=n;数组长度是这样的 while(i!=0&&j!=0) { if(c[i][j]==c[i-1][j-1]+1) { printf("%c",x[i-1]); i = i - 1; // 这两句是需要的 j = j - 1; } else if(c[i][j]==c[i-1][j]) i=i-1; else j=j-1; }}