def fit(sim_mat, D_len, cidx):
    min_energy = np.inf
    for j in range(3):
        inds = [np.argmin([sim_mat[idy].get(idx, 0) for idx in cidx]) for idy in range(D_len) if idy in sim_mat]
        cidx = []
        energy = 0
        for i in np.unique(inds):
            indsi = np.where(inds == i)[0]
            minind, min_value = 0, 0
            for index, idy in enumerate(indsi):
                if idy in sim_mat:
                    value = 0
                    for idx in indsi:
                        value += sim_mat[idy].get(idx, 0)
                    if value < min_value:
                        minind, min_value = index, value
            energy += min_value
            cidx.append(indsi[minind])
        if energy < min_energy:
            min_energy, inds_min, cidx_min = energy, inds, cidx
    return inds_min, cidx_min