例如 有一个map A :{a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9}
B:{a:1,b:2,c:3}
C:{c:3,d:4,e:5,f:6}
D:{d:4,e:5,f:6,g:7,h:8,i:9}
E:{a:1}
F:{c:3,d:4,e:5,f:6,g:7,h:8,i:9}
怎么写代码在B,C,D,E,F中找出可以组成包含A的最小子集。如BD可以,就是两个
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Q700376
{
class Program
{
static void Main(string[] args)
{
string mapa = @"A:{a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9}";
string othermaps = @"B:{a:1,b:2,c:3}
C:{c:3,d:4,e:5,f:6}
D:{d:4,e:5,f:6,g:7,h:8,i:9}
E:{a:1}
F:{c:3,d:4,e:5,f:6,g:7,h:8,i:9}";
var mapA = Regex.Match(mapa, @"(?<=\{).*?(?=\})").Value.Split(',').ToDictionary(x => x.Split(':')[0], x => x.Split(':')[1]);
var maps = othermaps.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)
.ToDictionary(y => y.Substring(0, 1), y => Regex.Match(y, @"(?<=\{).*?(?=\})").Value.Split(',').ToDictionary(x => x.Split(':')[0], x => x.Split(':')[1]));
List<string> result = new List<string>();
foreach (var k in maps.Keys)
solve(mapA, maps, k, x => result.Add(x));
Console.WriteLine(result.Distinct().OrderBy(x => x.Length).First());
}
private static void solve(Dictionary<string, string> mapA, Dictionary<string, Dictionary<string, string>> maps, string k, Action<string> callback)
{
foreach (var k1 in maps.Keys)
{
if (!k.Contains(k1))
{
var maps1 = maps.Where(x => x.Key != k.Last().ToString()).ToDictionary(x => x.Key, x => x.Value);
var mapA1 = mapA.Keys.Except(maps.First(y => y.Key == k.Last().ToString()).Value.Keys).ToDictionary(x => x, x => mapA[x]);
if (mapA1.Count == 0)
callback(k);
else
solve(mapA1, maps1, k + k1, callback);
}
}
}
}
}
BD
Press any key to continue . . .