Cod sursa(job #170097)

Utilizator sima_cotizoSima Cotizo sima_cotizo Data 2 aprilie 2008 13:22:02
Problema Subsir Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.22 kb
#include <cstdio>
#include <cstring>
#include <set>
#include <string>
using namespace std;
#define MAX_N 600

char A[MAX_N], B[MAX_N];
int D[MAX_N][MAX_N];
int i,j,n,m,mx;
set<string> M;

int max(int a, int b) { return a<b ? b : a; }
int mystrlen(char *p) {
	int x = strlen(p);
	while ( p[x-1]>'z' || p[x-1]<'a' ) p[--x] = 0;
	return x;
}

void create(int x, int y, string S) {
	if ( x<0 || y<0 ) return;
	if ( D[x][y]-D[x-1][y-1]==1 ) {
		create(x-1,y-1,S);
		S += A[x];
	} else {
		if ( D[x][y-1] < D[x-1][y] )
			create(x, y-1, S);
		else 
			create(x-1, y, S);
	}
}

int main() {
	freopen("subsir.in", "r", stdin);
	fgets(A, MAX_N, stdin);
	fgets(B, MAX_N, stdin);

	n = mystrlen(A);
	m = mystrlen(B);

	for (i=0; i<n; ++i)
		D[0][i] = (A[0]==B[i]);
	for (i=0; i<m; ++i)
		D[i][0] = (A[i]==B[0]);

	for (i=1; i<n; ++i)
		for (j=1; j<m; ++j)
			if ( A[i]==B[j] ) {
				D[i][j] = D[i-1][j-1]+1;
				if ( D[i][j] > mx ) 
					mx = D[i][j], M.clear();
				if ( D[i][j] == mx ) {
					string S;
					create(i,j,S);
					if ( M.find(S)==M.end() ) M.insert(S);
				}
			} else
				D[i][j] = max(D[i][j-1], D[i-1][j]);

	freopen("subsir.out", "w", stdout);
	printf("%d\n", M.size());
	return 0;
}