Cabala 50/100 Output errato

Salve, mi interessa fare 70/100 al problema cabala, ma purtroppo fallisco il testcase 003, questo è il mio codice, per favore potete aiutarmi? ottengo output non corretto, non TLE

#include <stdio.h>
#include <assert.h>
#include <bits/stdc++.h>
#include <vector>
#include <string>
using namespace std;
void permut(int X,vector<string> arr,int M,int *res,long long int mas)
{
    vector<string> ml;
    ml = arr;

    int count = ml.size();

    // Provo tutte le lunghezze
    for(int z = 0; z < X - 1; z++)
    {

        // Salvo le combinazioni di lunghezza z
        vector<string> tmp;


        // Attraverso l'array
        for(int i = 0; i < arr.size(); i++)
        {
            for(int k = 0; k < ml.size(); k++)
            {
                if (arr[i] != ml[k])
                {

                    // Genero le combinazioni di lunghezza z
                    tmp.push_back(ml[k] + arr[i]);
                    count += 1;
                }
            }
        }

        bool flag;
        for(int i = 0; i < tmp.size(); i++)
        {
            flag=true;
            for (int j=0;j<tmp[i].size();j++){
                    //cout<<"NUMERO "<<tmp[i]<< " "<<tmp[i][j]<<" = "<<tmp[i][j+1]<<endl;
                    if (tmp[i][j]== tmp[i][j+1]){
                        //cout<<" quindi false"<<endl;
                        flag=false;
                    }

                }
                if (flag){
                    cout<<"NUMERO VALIDO: "<<tmp[i]<<" % "<<M<<" = "<<stoll(tmp[i])%M<<" VECCHIOMASS= "<<mas<<endl;
                    if (mas<stoll(tmp[i])%M){
                        mas=stoll(tmp[i])%M;
                    }
                cout << mas << " ";}
        }*res=mas;

        // Replace all combinations of length z - 1
        // with all combinations of length z
        ml = tmp;
    }
}
int occulta(int N, int M) {
    int res=0;
    if (N==1){
        int mas=max((3%M),(6%M));
        return max(mas,(9%M));
    }
    permut(N,{"3","6","9"},M, &res,0);
    return res;

}


int main() {
    FILE *fr, *fw;
    int T, N, M, i;

    fr = fopen("input.txt", "r");
    fw = fopen("output.txt", "w");
    assert(1 == fscanf(fr, "%d", &T));
    for (i=0; i<T; i++) {
        assert(2 == fscanf(fr, "%d %d", &N, &M));
        fprintf(fw, "%d ", occulta(N, M));
    }

    fprintf(fw, "\n");
    fclose(fr);
    fclose(fw);
    return 0;
}