Pagini recente » Cod sursa (job #312193) | Cod sursa (job #2645174) | Cod sursa (job #2536810) | Cod sursa (job #3286315) | Cod sursa (job #3328714)
//
// main.cpp
// cmls
//
// Created by Rei on 09.12.2025.
//
#include <iostream>
#include <fstream>
using namespace std;
ifstream f ("subsir.in");
ofstream g ("subsir.out");
int n, m;
char a[1024], b[1024];
int d[1030][1030];
unsigned long long cnt[1030][1030];
int v[101];
int main()
{
f>>n>>m;
for (int i = 1; i <= n; ++i){
f >> ws; f.get(a[i]);
}
for (int i = 1; i <= m; ++i){
f >> ws; f.get(b[i]);
}
// initialize borders for DP
for (int i = 0; i <= n; ++i) {
d[i][0] = 0;
cnt[i][0] = 1; // one empty subsequence
}
for (int j = 0; j <= m; ++j) {
d[0][j] = 0;
cnt[0][j] = 1; // one empty subsequence
}
for (int i = 1; i <= n; ++i){
for (int j = 1; j <= m; ++j){
if (a[i] == b[j]){
d[i][j] = d[i-1][j-1] + 1;
cnt[i][j] = cnt[i-1][j-1];
}
else {
if (d[i-1][j] > d[i][j-1]) {
d[i][j] = d[i-1][j];
cnt[i][j] = cnt[i-1][j];
} else if (d[i-1][j] < d[i][j-1]) {
d[i][j] = d[i][j-1];
cnt[i][j] = cnt[i][j-1];
} else { // equal lengths
d[i][j] = d[i-1][j];
cnt[i][j] = cnt[i-1][j] + cnt[i][j-1];
if (d[i-1][j-1] == d[i][j]) {
cnt[i][j] -= cnt[i-1][j-1];
}
}
}
}
}
int mx = d[n][m];
int i=n,j=m,k=0;
while(mx>0)
{
if(a[i]==b[j])
{
k++;
v[k]=a[i];
i--;
j--;
mx--;
}
else{
if(i>0 && d[i-1][j]==mx)
i--;
else
j--;
}
}
g<<d[n][m]<<'\n';
g<<cnt[n][m]<<'\n';
for (int l = k; l >= 1; l--)
{
g << static_cast<char>(v[l]) << " ";
}
}