#include <stdio.h>

#define FAIL -1
#define OK 0
#define N ('z'-'a'+1)

void get_data(char *f, float a[N][N]){
    FILE *fin;
    int i; 
    float v;
    char x,y;
    fin=fopen(f, "r");
    for(i=0; i<N*N; i++){
        fscanf(fin, "%c%c %f\n", &x, &y, &v);
        a[x-'a'][y-'a']=v;
    }
    close(fin);
    return;
}

void max(float a[N][N], char *x, char *y){
    int i,j;
    float fmax=-1;
    char maxi='\0';
    char maxj='\0';
    for(i=0; i<N; i++)
       for(j=0; j<N; j++) 
            if (a[i][j]>fmax) {
                fmax=a[i][j];
                maxi=i;
                maxj=j;
            }
    a[maxi][maxj]=-1;
    *x= maxi+'a';
    *y= maxj+'a';
    return;
}

void sort(float a[N][N], char r[N*N][2]){
    int i;
    for(i=0; i<N*N; i++){
        char x, y;
        max(a, &x, &y);
        r[i][0]=x;
        r[i][1]=y;
    }
    return;
}

char maxcount(int a[N]){
    int max=0, i;
    char c='*';
    for(i=0; i<N; i++)
        if (max<a[i]){
            max=a[i];
            c='a'+i;
        }
    return c;
}

char get_letter(char lg[N*N][2], char cr[N*N][2], char l){
    int i;
    int collect[N]={0};
    for(i=0; i<N*2; i++)
        if (cr[i][0]==l){
            collect[lg[i][0]-'a']+=1;
        } else if (cr[i][1]==l){
            collect[lg[i][1]]+=1;
        }
    return maxcount(collect);
}

int in(char s[N], char c){
    int i;
    for(i=0; i<N; i++) 
        if (s[i]==c) return 1;
    return 0;
}

void get_subst(char lg[N*N][2], char cr[N*N][2], char res[N]){
    int count=0, i;
    for(i=0; i<N; i++) res[i]=0;
    for(i=0; count<N && i<N*N; i++){
        char l1 = lg[i][0] -'a';
        char l2 = lg[i][1] -'a';
        char c1 = cr[i][0];
        char c2 = cr[i][1];
        if (res[l1]==0 && !in(res,c1)) { res[l1]=c1; count++; }
        if (res[l2]==0 && !in(res,c2)) { res[l2]=c2; count++; }
    }
    return;
}

int main(int argc, char **argv){
    float freqs_cr[N][N]={0};
    float freqs_lg[N][N]={0};
    char cr[N*N][2], lg[N*N][2], c;
    char res[N];
    if (argc<3) return FAIL;
   
    get_data(argv[1], freqs_cr);
    sort(freqs_cr, cr);
    //printf("Alphabet of ciphertext sorted by frequency: %s\n",cr);
    get_data(argv[2], freqs_lg);
    sort(freqs_lg, lg);
    //printf("Alphabet of target language sorted by frequency: %s\n",lg);
    for(c='a'; c<='z'; c++)
        printf("%c", get_letter(lg, cr, c));
    printf("\n");
    get_subst(lg, cr, res);
    printf("%s\n", res);
    return OK;
}

