Pagini recente » Cod sursa (job #3208059) | Cod sursa (job #2682699) | Cod sursa (job #586539) | Cod sursa (job #261338) | Cod sursa (job #1464929)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define nmax 505
#define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
#define star(i, j) (s1[i] == s2[j] ? 1 : 0)
char s1[nmax], s2[nmax];
int n1, n2, i, j, lcs[nmax][nmax], nr[nmax][nmax];
void calc_lcs()
{
lcs[1][1] = (s1[1] == s2[1] ? 1 : 0);
for (i = 2; i <= n1; i++)
lcs[i][1] = (lcs[i-1][1] || (s1[i] == s2[1] ? 1 : 0));
for (j = 2; j <= n2; j++)
lcs[1][j] = (lcs[1][j-1] || (s1[1] == s2[j] ? 1 : 0));
for (i = 2; i <= n1; i++)
for (j = 2; j <= n2; j++)
lcs[i][j] = (s1[i] == s2[j] ? lcs[i-1][j-1] + 1 : MAX(lcs[i][j-1], lcs[i-1][j]));
}
void calc_nr()
{
for (i = 0; i <= n1; i++)
nr[i][0] = 1;
for (j = 0; j <= n2; j++)
nr[0][j] = 1;
for (i = 1; i <= n1; i++)
for (j = 1; j <= n2; j++)
{
if (star(i, j))
nr[i][j] = nr[i-1][j-1];
else if (lcs[i][j-1] == lcs[i-1][j])
{
nr[i][j] = (nr[i-1][j] + nr[i][j-1])%666013;
if (lcs[i][j-1] == lcs[i-1][j-1])
nr[i][j] = (nr[i][j] - nr[i-1][j-1])%666013;
nr[i][j] = (nr[i][j] >= 0 ? nr[i][j] : nr[i][j] + 666013);
}
else
nr[i][j] = (MAX(lcs[i][j-1], lcs[i-1][j]) == lcs[i][j-1] ? nr[i][j-1] : nr[i-1][j]);
}
}
void print(int a[nmax][nmax])
{
for (i = 1; i <= n1; i++)
{
for (j = 1; j <= n2; j++)
{
//if (star(i, j))
printf("%d ", a[i][j]);
//else
// printf("0 ", a[i][j]);
}
printf("\n");
}
printf("\n");
}
int main()
{
FILE *in, *out;
in = fopen("subsir.in", "r");
out = fopen("subsir.out", "w");
fgets(&s1[1], nmax+1, in);
fgets(&s2[1], nmax+1, in);
n1 = strlen(&s1[1]);
n2 = strlen(&s2[1]);
/* delete '\n' ending the strings if the case */
if (s1[n1] < 'a' || s1[n1] > 'z')
s1[(n1--)] = 0;
if (s2[n2] < 'a' || s2[n2] > 'z')
s2[(n2--)] = 0;
calc_lcs();
calc_nr();
/*print(lcs);
print(nr);
getchar();*/
fprintf(out, "%d\n", nr[n1][n2]);
fclose(in);
fclose(out);
return 0;
}