Dynamic D2D Communication in 5G/6G Using a Distributed AI Framework