有没有人可以分享一个用java编写的程序,它可以做以下工作。如果给定以下集合作为输入,
a={1,2,3,8,9,10}
b={1,2,3,4,5}
c={4,5,7}
d={5,6,7}
e={6,7,8,9,10}和
U={1,2,3,4,5,6,7,8,9,10}程序将找到集合的所有组合,并找出集合的最小数量,这些集合一起具有U的所有元素。
在上面的例子中,最小的数目是2。集合b和e一起覆盖了所有的U。所以基本上,这是一个集合覆盖问题。在集合覆盖问题中,我们被给予一个论域U,使得|U|=n和集合S1,……,Sk是U的子集。集合覆盖是来自S1,……,Sk的一些集合的集合C,这些集合的并集是整个论域U。此外,我们必须最小化集合的成本。
发布于 2010-11-27 01:54:46
您需要的是测试组合大小的增加,如下所示
interface Filter<T> {
boolean matches(T t);
}
public static void main(String... args) throws IOException {
Integer[][] arrayOfSets = {
{1, 2, 3, 8, 9, 10},
{1, 2, 3, 4, 5},
{4, 5, 7},
{5, 6, 7},
{6, 7, 8, 9, 10},
};
Integer[] solution = {1,2,3,4,5,6,7,8,9,10};
List<Set<Integer>> listOfSets = new ArrayList<Set<Integer>>();
for (Integer[] array : arrayOfSets)
listOfSets.add(new LinkedHashSet<Integer>(Arrays.asList(array)));
final Set<Integer> solutionSet = new LinkedHashSet<Integer>(Arrays.asList(solution));
Filter<Set<Set<Integer>>> filter = new Filter<Set<Set<Integer>>>() {
public boolean matches(Set<Set<Integer>> integers) {
Set<Integer> union = new LinkedHashSet<Integer>();
for (Set<Integer> ints : integers)
union.addAll(ints);
return union.equals(solutionSet);
}
};
Set<Set<Integer>> firstSolution = shortestCombination(filter, listOfSets);
System.out.println("The shortest combination was "+firstSolution);
}
private static <T> Set<T> shortestCombination(Filter<Set<T>> filter, List<T> listOfSets) {
final int size = listOfSets.size();
if (size > 20) throw new IllegalArgumentException("Too many combinations");
int combinations = 1 << size;
List<Set<T>> possibleSolutions = new ArrayList<Set<T>>();
for(int l = 0;l<combinations;l++) {
Set<T> combination = new LinkedHashSet<T>();
for(int j=0;j<size;j++) {
if (((l >> j) & 1) != 0)
combination.add(listOfSets.get(j));
}
possibleSolutions.add(combination);
}
// the possible solutions in order of size.
Collections.sort(possibleSolutions, new Comparator<Set<T>>() {
public int compare(Set<T> o1, Set<T> o2) {
return o1.size()-o2.size();
}
});
for (Set<T> possibleSolution : possibleSolutions) {
if (filter.matches(possibleSolution))
return possibleSolution;
}
return null;
}打印
The shortest combination was [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]发布于 2011-01-06 02:29:09
很抱歉,回复晚了。但如果你仍然对此感兴趣,你可以使用Rajagopalan-Vazirani算法获得设置封面的近似解:http://portal.acm.org/citation.cfm?id=299880。这将给出最多偏离最优的因子2的答案。
发布于 2020-07-16 00:43:36
Let I表示到目前为止包含的元素集。
初始化I = {}的
当U与不同时,
I执行以下操作- a) Find the set `Si` in `{S1, S2, ... Sm}` whose cost effectiveness is smallest.
- b) Add elements of above picked `Si` to `I`, i.e., `I = I U Si`.https://stackoverflow.com/questions/4287302
复制相似问题