// Noyau repris de Coalitions-03 : graphe de compatibilite, cycles, chaines altruistes.
// Instance fixee (meme semence que 03, reproductible) : le generateur ci-dessous
// reproduit le flux de random.Random(12240) de CPython terme a terme, donc les
// six paires mesurees sont celles du carnet Python.
var rng = new Mt19937(12240);
var groupes = new[] { "O", "A", "B", "AB" };
var paires = new (string donneur, string receveur)[6];
for (int i = 0; i < paires.Length; i++) paires[i] = (rng.Choice(groupes), rng.Choice(groupes));
var altruistes = new[] { "B", "B" };
var gSans = Noyau03.ConstruireGrapheAvecAltruistes(paires, Array.Empty<string>());
var gAvec = Noyau03.ConstruireGrapheAvecAltruistes(paires, altruistes);
Console.WriteLine("Paires (donneur, receveur) : [" + string.Join(", ", paires.Select(p => "('" + p.donneur + "', '" + p.receveur + "')")) + "]");
Console.WriteLine("Altruistes : [" + string.Join(", ", altruistes.Select(a => "'" + a + "'")) + "]");
Console.WriteLine("Aretes sans altruiste : " + Noyau03.NombreAretes(gSans) + " | avec : " + Noyau03.NombreAretes(gAvec));
// Assertion : les six paires mesurees sont celles de la source.
var pairesAttendues = new[] { "('B', 'B')", "('AB', 'O')", "('B', 'B')", "('O', 'AB')", "('A', 'AB')", "('AB', 'B')" };
var pairesMesurees = paires.Select(p => "('" + p.donneur + "', '" + p.receveur + "')").ToArray();
if (!pairesMesurees.SequenceEqual(pairesAttendues))
throw new Exception("paires differentes de la source : " + string.Join(", ", pairesMesurees));
if (Noyau03.NombreAretes(gSans) != 9 || Noyau03.NombreAretes(gAvec) != 15)
throw new Exception("nombre d'aretes different de la source");
/// Generateur MT19937 : meme initialisation et meme consommation que
/// random.Random(seed) de CPython (init_by_array + getrandbits avec rejet).
public sealed class Mt19937
{
const int N = 624;
const int M = 397;
const uint MatrixA = 0x9908b0dfU;
const uint UpperMask = 0x80000000U;
const uint LowerMask = 0x7fffffffU;
readonly uint[] _mt = new uint[N];
int _mti;
public Mt19937(int seed) { InitByArray(new uint[] { unchecked((uint)Math.Abs((long)seed)) }); }
void InitGenrand(uint s)
{
_mt[0] = s;
for (int i = 1; i < N; i++)
_mt[i] = unchecked(1812433253U * (_mt[i - 1] ^ (_mt[i - 1] >> 30)) + (uint)i);
_mti = N;
}
void InitByArray(uint[] key)
{
InitGenrand(19650218U);
int i = 1, j = 0;
int k = Math.Max(N, key.Length);
for (; k > 0; k--)
{
_mt[i] = unchecked((uint)((_mt[i] ^ ((_mt[i - 1] ^ (_mt[i - 1] >> 30)) * 1664525U)) + key[j] + (uint)j));
i++;
j++;
if (i >= N) { _mt[0] = _mt[N - 1]; i = 1; }
if (j >= key.Length) j = 0;
}
for (k = N - 1; k > 0; k--)
{
_mt[i] = unchecked((uint)((_mt[i] ^ ((_mt[i - 1] ^ (_mt[i - 1] >> 30)) * 1566083941U)) - (uint)i));
i++;
if (i >= N) { _mt[0] = _mt[N - 1]; i = 1; }
}
_mt[0] = 0x80000000U;
}
public uint NextUInt32()
{
uint y;
if (_mti >= N)
{
int kk;
for (kk = 0; kk < N - M; kk++)
{
y = (_mt[kk] & UpperMask) | (_mt[kk + 1] & LowerMask);
_mt[kk] = _mt[kk + M] ^ (y >> 1) ^ ((y & 1U) != 0U ? MatrixA : 0U);
}
for (; kk < N - 1; kk++)
{
y = (_mt[kk] & UpperMask) | (_mt[kk + 1] & LowerMask);
_mt[kk] = _mt[kk + (M - N)] ^ (y >> 1) ^ ((y & 1U) != 0U ? MatrixA : 0U);
}
y = (_mt[N - 1] & UpperMask) | (_mt[0] & LowerMask);
_mt[N - 1] = _mt[M - 1] ^ (y >> 1) ^ ((y & 1U) != 0U ? MatrixA : 0U);
_mti = 0;
}
y = _mt[_mti++];
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680U;
y ^= (y << 15) & 0xefc60000U;
y ^= (y >> 18);
return y;
}
public ulong GetRandBits(int k)
{
int words = (k - 1) / 32 + 1;
ulong result = 0;
for (int i = 0; i < words; i++)
{
uint r = NextUInt32();
int bits = k - i * 32;
if (bits < 32) r >>= (32 - bits);
result |= (ulong)r << (i * 32);
}
return result;
}
/// _randbelow de CPython : tire k bits et rejette tant que le resultat depasse n.
public int RandBelow(int n)
{
int k = 32 - BitsEnTete((uint)n);
ulong r = GetRandBits(k);
while (r >= (ulong)n) r = GetRandBits(k);
return (int)r;
}
static int BitsEnTete(uint v)
{
if (v == 0) return 32;
int c = 0;
while ((v & 0x80000000U) == 0) { v <<= 1; c++; }
return c;
}
public T Choice<T>(IReadOnlyList<T> seq) => seq[RandBelow(seq.Count)];
}
/// Graphe dirige de compatibilite entre paires donneur-receveur et donneurs altruistes.
public sealed class Graphe
{
public sealed class Noeud
{
public string Role { get; }
public string Donneur { get; }
public string Receveur { get; }
public Noeud(string role, string donneur, string receveur) { Role = role; Donneur = donneur; Receveur = receveur; }
}
readonly Dictionary<string, Noeud> _noeuds = new Dictionary<string, Noeud>();
readonly Dictionary<string, List<string>> _arcs = new Dictionary<string, List<string>>();
public void Add(string id, string role, string donneur, string receveur)
{
_noeuds[id] = new Noeud(role, donneur, receveur);
if (!_arcs.ContainsKey(id)) _arcs[id] = new List<string>();
}
public void AddArc(string a, string b) => _arcs[a].Add(b);
public IReadOnlyList<string> Successeurs(string id) => _arcs[id];
public IEnumerable<string> Noeuds => _noeuds.Keys;
public Noeud Info(string id) => _noeuds[id];
public int NombreAretes() => _arcs.Values.Sum(v => v.Count);
public Graphe Copy()
{
var g = new Graphe();
foreach (var kv in _noeuds) g.Add(kv.Key, kv.Value.Role, kv.Value.Donneur, kv.Value.Receveur);
foreach (var kv in _arcs) foreach (var v in kv.Value) g.AddArc(kv.Key, v);
return g;
}
public void Remove(IEnumerable<string> ids)
{
foreach (var id in ids) { _noeuds.Remove(id); _arcs.Remove(id); }
foreach (var kv in _arcs) kv.Value.RemoveAll(x => !_noeuds.ContainsKey(x));
}
}
public static class Noyau03
{
public static Graphe ConstruireGrapheAvecAltruistes((string donneur, string receveur)[] paires, string[] altruistes)
{
var g = new Graphe();
for (int i = 0; i < paires.Length; i++) g.Add("P" + i, "paire", paires[i].donneur, paires[i].receveur);
for (int j = 0; j < altruistes.Length; j++) g.Add("A" + j, "altruiste", altruistes[j], null);
for (int j = 0; j < altruistes.Length; j++)
for (int i = 0; i < paires.Length; i++)
if (altruistes[j] == paires[i].receveur) g.AddArc("A" + j, "P" + i);
for (int i = 0; i < paires.Length; i++)
for (int k = 0; k < paires.Length; k++)
if (i != k && paires[i].donneur == paires[k].receveur) g.AddArc("P" + i, "P" + k);
return g;
}
public static int NombreAretes(Graphe g) => g.NombreAretes();
/// Couverture gloutonne : cycles de paires disjoints, les plus longs d'abord.
public static List<List<string>> CouvertureParCycles(Graphe g, int kMax)
{
var noeuds = g.Noeuds.Where(n => g.Info(n).Role == "paire").OrderBy(n => n, StringComparer.Ordinal).ToList();
var candidats = new List<List<string>>();
foreach (var depart in noeuds)
{
var chemin = new List<string> { depart };
EnumCycles(g, noeuds, kMax, noeuds.IndexOf(depart), chemin, new HashSet<string> { depart }, candidats);
}
var tries = candidats.OrderByDescending(c => c.Count).ToList();
var pris = new List<List<string>>();
var prisDans = new HashSet<string>();
foreach (var c in tries)
{
if (c.Any(x => prisDans.Contains(x))) continue;
pris.Add(c);
foreach (var x in c) prisDans.Add(x);
}
return pris;
}
static void EnumCycles(Graphe g, List<string> noeuds, int kMax, int indexDepart, List<string> chemin, HashSet<string> surChemin, List<List<string>> acc)
{
string courant = chemin[chemin.Count - 1];
if (chemin.Count > 1 && g.Successeurs(courant).Contains(chemin[0]))
{
var cycle = Canonique(chemin);
if (!acc.Any(c => c.SequenceEqual(cycle))) acc.Add(cycle);
return;
}
if (chemin.Count >= kMax) return;
foreach (var succ in g.Successeurs(courant))
{
if (surChemin.Contains(succ)) continue;
int index = noeuds.IndexOf(succ);
if (index < indexDepart) continue;
chemin.Add(succ);
surChemin.Add(succ);
EnumCycles(g, noeuds, kMax, indexDepart, chemin, surChemin, acc);
chemin.RemoveAt(chemin.Count - 1);
surChemin.Remove(succ);
}
}
/// Cycle canonique : plus petit noeud en tete, puis orientation minimale.
static List<string> Canonique(List<string> cycle)
{
int meilleur = 0;
for (int i = 1; i < cycle.Count; i++)
if (string.CompareOrdinal(cycle[i], cycle[meilleur]) < 0) meilleur = i;
var rot = new List<string>();
for (int i = 0; i < cycle.Count; i++) rot.Add(cycle[(meilleur + i) % cycle.Count]);
var inverse = new List<string> { rot[0] };
for (int i = rot.Count - 1; i >= 1; i--) inverse.Add(rot[i]);
for (int i = 1; i < rot.Count; i++)
{
int c = string.CompareOrdinal(rot[i], inverse[i]);
if (c != 0) return c < 0 ? rot : inverse;
}
return rot;
}
/// Chaines demarrees par un altruiste (DFS bornee), reprises de 03 tel quel.
/// Le graphe recu est celui sur lequel la chaine a le DROIT de courir : pour un
/// plan combine cycles + chaine, c'est le graphe residuel (paires non servies).
public static List<List<string>> EnumererChaines(Graphe g, int kMax)
{
var chaines = new List<List<string>>();
foreach (var source in g.Noeuds.Where(n => g.Info(n).Role == "altruiste"))
DfsChaines(g, source, new List<string> { source }, 0, kMax, chaines);
return chaines;
}
static void DfsChaines(Graphe g, string noeud, List<string> chemin, int profondeur, int kMax, List<List<string>> acc)
{
if (profondeur >= kMax) { acc.Add(new List<string>(chemin)); return; }
foreach (var succ in g.Successeurs(noeud))
{
if (chemin.Contains(succ)) continue;
chemin.Add(succ);
DfsChaines(g, succ, chemin, profondeur + 1, kMax, acc);
chemin.RemoveAt(chemin.Count - 1);
}
if (profondeur >= 1) acc.Add(new List<string>(chemin));
}
/// Couverture par cycles d'abord, puis chaine sur le graphe RESIDUEL.
/// Contrainte du monde : un donneur ne donne qu'une fois. Une paire servie par un
/// cycle ne peut donc pas etre traversee par une chaine -- enumerer les chaines sur
/// le graphe complet fabriquerait des plans infaisables ou une meme paire donne deux fois.
public static (List<List<string>> cycles, List<string> meilleure, HashSet<string> servies) CouvertureCyclesPuisChaine(
(string donneur, string receveur)[] paires, string[] altruistes, int kCycles, int kChaine)
{
var g = ConstruireGrapheAvecAltruistes(paires, altruistes);
var cycles = CouvertureParCycles(g, kCycles);
var servies = new HashSet<string>();
foreach (var c in cycles) foreach (var x in c) servies.Add(x);
var residuel = g.Copy();
residuel.Remove(servies);
var chaines = EnumererChaines(residuel, kChaine);
var meilleure = new List<string>();
int gainMax = -1, longueurMax = -1;
foreach (var ch in chaines)
{
int gain = ch.Count(x => x.StartsWith("P") && !servies.Contains(x));
if (gain > gainMax || (gain == gainMax && ch.Count > longueurMax))
{
meilleure = new List<string>(ch);
gainMax = gain;
longueurMax = ch.Count;
}
}
foreach (var x in meilleure) if (x.StartsWith("P")) servies.Add(x);
return (cycles, meilleure, servies);
}
/// Formatage des noeuds a la maniere du carnet source : ('P', 0).
public static string Tuple(string id) => "('" + id.Substring(0, 1) + "', " + id.Substring(1) + ")";
}