private static train Merge(List <train> ttrs, char ch) { train ntr = new train(); int ibc = 0, iec = 0; foreach (train tr in ttrs) { if (tr.cb != ch) { ibc++; ntr.cb = tr.cb; } if (tr.ce != ch) { iec++; ntr.ce = tr.ce; } foreach (char cch in tr.ccnt) { if (!ntr.ccnt.Contains(cch)) { ntr.ccnt.Add(cch); } } foreach (char mch in tr.cmid) { if (!ntr.cmid.Contains(mch)) { ntr.cmid.Add(mch); } } } if (ibc > 1 || iec > 1) { return(ntr); } if (ibc == 1 && iec == 1 && ntr.cb == ntr.ce) { return(ntr); } int iwc = ttrs.Count - 2; int iw = 1; if (ibc == 0) { ntr.cb = ch; iwc++; } if (iec == 0) { ntr.ce = ch; iwc++; } while (iwc > 1) { iw = (int)(Math.BigMul(iw, iwc) % mdl); iwc--; } foreach (train tr in ttrs) { iw = (int)(Math.BigMul(iw, tr.ways) % mdl); } ntr.ways = iw; return(ntr); }
public static string Solve(List <train> trains) { List <char> chs = new List <char>(); for (int i = 0; i < trains.Count; i++) { if (trains[i].ways == 0) { return("0"); } foreach (char mch in trains[i].cmid) { for (int j = 0; j < trains.Count; j++) { if (i == j) { continue; } if (trains[j].ccnt.Contains(mch)) { return("0"); } } } foreach (char ch in trains[i].ccnt) { if (!chs.Contains(ch)) { chs.Add(ch); } } } foreach (char ch in chs) { List <train> ttrs = trains.FindAll(t => t.ccnt.Contains(ch)); train ntr = Merge(ttrs, ch); if (ntr.ways == 0) { return("0"); } foreach (train tr in ttrs) { trains.Remove(tr); } trains.Add(ntr); } int iw = 1; int iwc = trains.Count; while (iwc > 1) { //iw = (iw * iwc) % mdl; iw = (int)(Math.BigMul(iw, iwc) % mdl); iwc--; } foreach (train tr in trains) { iw = (int)(Math.BigMul(iw, tr.ways) % mdl); //iw = (iw * tr.ways) % mdl; } return(iw.ToString()); }