• + 0 comments

    using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Solution { public static int CountIslands(string s, string p) { int n = s.Length; int m = p.Length; bool[] marked = new bool[n]; // Mark positions covered by substring p using Parallel.For Parallel.For(0, n - m + 1, i => { if (s.Substring(i, m) == p) { for (int j = i; j < i + m; j++) { marked[j] = true; } } }); // Count islands using LINQ int islands = marked .Select((value, index) => new { value, index }) .Aggregate( new { Count = 0, InIsland = false }, (acc, item) => item.value ? acc.InIsland ? acc : new { Count = acc.Count + 1, InIsland = true } : new { Count = acc.Count, InIsland = false }, acc => acc.Count ); return islands; } public static int CountSubstringsWithKIslands(string s, int k) { var substrings = new ConcurrentDictionary(); int n = s.Length; // Generate all substrings and count islands using PLINQ var allSubstrings = from i in Enumerable.Range(0, n) from j in Enumerable.Range(i + 1, n - i) select s.Substring(i, j - i); Parallel.ForEach(allSubstrings.Distinct(), substring => { int islands = CountIslands(s, substring); if (islands == k) { substrings.TryAdd(substring, true); } }); return substrings.Count; } static async Task Main(string[] args) { string s = Console.ReadLine(); int k = int.Parse(Console.ReadLine()); int result = await Task.Run(() => CountSubstringsWithKIslands(s, k)); Console.WriteLine(result); } }