Caesar Cypher, problemi di tempo

#include<bits/stdc++.h>

using namespace std;

int main(){
    int N, D, risF=1;
    cin >> N >> D;
    vector<string> word(N);
    vector<int> R(N, 0);
    for(int i=0; i<N; i++){
        cin >> word[i];
    }
    for(int i=0;i<N;i++){
        if(R[i]==0){
            int ris=1;
            for(int j=i+1;j<N; j++){
                if(R[j]==0){
                    char cost;
                    if(word[i][0]-word[j][0]<0)
                        cost=word[i][0]-word[j][0]+26;
                    else
                        cost=word[i][0]-word[j][0];
                    int t=0;
                    for(int z=1;z<D;z++){
                        char cost2;
                        if(word[i][z]-word[j][z]<0)
                            cost2=word[i][z]-word[j][z]+26;
                        else
                            cost2=word[i][z]-word[j][z];
                        if(cost!=cost2){
                            t=1;
                            break;
                        }
                    }
                    if(t==0){
                        ris++;
                        R[j]=1;
                    }
                }
            }
            if(risF<ris)
                risF=ris;
        }
    }
    cout << risF << endl;
}

Non so come ottimizzare, idee?

Attualmente la tua soluzione va fuori tempo perché per ogni stringa cerchi fra tutte le altre se sono della stessa pila, con una complessità di O(N^2 * D).
Puoi evitare la ricerca utilizzando un unordered_map, stando attento ad utilizzare una versione “normalizzata” della stringa (ad esempio puoi decidere che debba partitre con la a e quindi modificare tutti i caratteri di conseguenza).
Poi puoi iterare tutta la mappa e trovare il massimo, con una complessità finale di O(N*D) che sta nei limiti del problema.