私は私の論理が何であるかについてのコメントを残しました。たとえば、K=3
とS={1,7,2,4}
がある場合、すべてのペアの合計がK
を除外しない最大のサブセットは{1,7,4}
です。 2つ目のループでは私のアルゴリズムの欠点は、すべてのペアの和がKを分けない最大の部分集合を見つけることですか?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
int k = Int32.Parse(Console.ReadLine().Split(' ')[1]);
var S = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);
// first get all pairs in S whose sum doesn't divide k,
// each pair in their own subset set of S
var subsets = from i in S
from j in S
where i < j && ((i + j) % k != 0)
select new HashSet<int>() { i, j };
// for each subset, for each number in the original set
// not already in the subset, if the number summed with
// every numer in the subset doesn't divide k, add the
// number to the subset
foreach(var ss in subsets)
foreach(int n in S.Where(q => !ss.Contains(q)))
if(ss.All(m => (m + n) % k != 0))
ss.Add(n);
// get the size of the largest subset, print to console
int max = subsets.Select(ss => ss.Count).Max();
Console.WriteLine(max);
}
}
入力に失敗する可能性はありますか? – yossico
私の例のものは失敗します。その例はhttps://www.hackerrank.com/challenges/non-divisible-subset?h_r=next-challenge&h_v=zen – user6048670
からですLINQクエリを実現する必要があることを認識するまで投稿する予定の質問は何ですか?それらが複数回使用される場合には、いくつかのメモリコレクションに格納されます。 'subsets.Select(..'は新しい 'HastSet'sを作成して、前のループでやったことをすべて投げてしまいます。 –