给定n个多种颜色的球,如何将球分组,保证每组内球颜色不能相同,且分组的数量要最小。

发布时间 2023-08-18 19:51:23作者: WinChance

using
System; using System.Collections.Generic; public class BallColorGroup { public int Color { get; set; } public int Count { get; set; } } public class BallColorGrouping { public static List<List<int>> GroupBalls(List<int> colors) { Dictionary<int, int> colorCount = new Dictionary<int, int>(); // 统计每种颜色球的数量 foreach (int color in colors) { if (!colorCount.ContainsKey(color)) { colorCount[color] = 0; } colorCount[color]++; } List<List<int>> groups = new List<List<int>>(); // 对颜色球按照数量由多到少进行排序 var sortedColors = colorCount.Keys; Array.Sort(sortedColors.ToArray(), ((a, b) => colorCount[b].CompareTo(colorCount[a]))); foreach (int color in sortedColors) { int count = colorCount[color]; // 在现有分组里查找能放置当前颜色的分组 bool groupFound = false; foreach (List<int> group in groups) { // 检查分组中是否有相同颜色的球 if (!group.Contains(color)) { group.Add(color); count--; groupFound = true; break; } } // 如果找不到能放置当前颜色的分组,则创建新的分组 if (!groupFound) { List<int> newGroup = new List<int> { color }; count--; groups.Add(newGroup); } // 将剩余颜色球加入新分组中 while (count > 0) { List<int> newGroup = new List<int> { color }; count--; groups.Add(newGroup); } } return groups; } public static void Main(string[] args) { List<int> ballColors = new List<int> { 1, 2, 1, 3, 2, 4, 5, 3, 5, 4, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6 }; List<List<int>> colorGroups = GroupBalls(ballColors); // 输出分组结果 for (int i = 0; i < colorGroups.Count; i++) { Console.WriteLine($"Group {i + 1}: {string.Join(", ", colorGroups[i])}"); } } }