讓我們說你有名單α
,β
和ɣ
。
讓ABC = α ∩ β ∩ ɣ
讓AB = α ∩ β \ ABC
讓AC = α ∩ ɣ \ ABC
讓BC = β ∩ ɣ \ ABC
讓A = α \ (β ∪ ɣ)
讓B = β \ (α ∪ ɣ)
讓C = ɣ \ (α ∪ β)
讓| X |是集合X的基數。
返回true,當且僅當|A| + |B| + |C| + |AB| + |AC| + |BC| + |ABC| >= 3
實現示例:
void Main()
{
var alpha = new List<string> { "apple", "pear", };
var beta = new List<string> { "banana", };
var gamma = new List<string> { "banana", "apple", };
Console.WriteLine(Compute(alpha, beta, gamma));
Console.WriteLine(ComputeWithSets(alpha, beta, gamma));
alpha = new List<string> { "apple", "pear", };
beta = new List<string> { "apple", "pear", };
gamma = new List<string> { "apple", "pear", };
Console.WriteLine(Compute(alpha, beta, gamma));
Console.WriteLine(ComputeWithSets(alpha, beta, gamma));
alpha = new List<string> { "apple", "pear", "banana", };
beta = new List<string> { "apple", "pear", "banana", };
gamma = new List<string> { "apple", "pear", "banana", };
Console.WriteLine(Compute(alpha, beta, gamma));
Console.WriteLine(ComputeWithSets(alpha, beta, gamma));
}
bool Compute(List<string> alpha, List<string> beta, List<string> gamma)
{
if (alpha.Count == 0) return false;
if (beta.Count == 0) return false;
if (gamma.Count == 0) return false;
foreach (var a in alpha)
foreach (var b in beta)
if (a != b)
foreach (var c in gamma)
if (c != a && c != b)
{
Console.Write(string.Format("{0},{1},{2} =>", a, b, c));
return true;
}
return false;
}
bool ComputeWithSets(List<string> alpha, List<string> beta, List<string> gamma)
{
var abc = alpha.Intersect(beta.Intersect(gamma));
var abcCardinality = abc.Count();
var count = abcCardinality;
if (count >= 3) return true;
var ab = alpha.Intersect(beta).Except(abc);
count += ab.Count();
if (count >= 3) return true;
var bc = beta.Intersect(gamma).Except(abc);
count += bc.Count();
if (count >= 3) return true;
var ac = alpha.Intersect(gamma).Except(abc);
count += ac.Count();
if (count >= 3) return true;
var a = alpha.Except(ab).Except(ac).Except(abc);
count += a.Count();
if (count >= 3) return true;
var b = beta.Except(ab).Except(bc).Except(abc);
count += b.Count();
if (count >= 3) return true;
var c = gamma.Except(ac).Except(bc).Except(abc);
count += c.Count();
if (count >= 3) return true;
return false;
}
解決此問題的一種方法是創建一棵樹,每個級別都有一個列表中的所有可能性。之後,使用任何樹搜索算法都可以工作。 – Th0rndike
謝謝...我已經搜索了一些樹木,但我不知道如何實現這種情況! –
我認爲你應該改寫這個_我可以從每個列表中選擇一個項目,並確保每個選擇的項目都與其他選擇的項目不同 - 比如說**在每個列表中取一項,是否有可能有沒有重複?** – hoang