namespace PriorityQueueDemo {public class Task{public string Name { get; set; } }public class TaskPriorityComparer : IComparer<(int, int)>{public int Compare((int, int) x, (int, int) y){// 首先比较紧急程度,然后比较重要性int compareUrgency = x.Item1.CompareTo(y.Item1);if (compareUrgency != 0) return compareUrgency;return x.Item2.CompareTo(y.Item2);}}internal class Program{static void Main(string[] args){// 优先队列是一种特殊的队列,其中每个元素都有一个优先级。元素按照优先级的顺序被移除,而不是它们被添加到队列中的顺序。这意味着高优先级的元素将会在低优先级的元素之前被处理// 值越小等级越高// 简单的优先队列var priorityQueue1 = new PriorityQueue<string, int>();// 向队列中添加元素和对应的优先级priorityQueue1.Enqueue("任务高", 1);priorityQueue1.Enqueue("任务低", 3);priorityQueue1.Enqueue("任务中", 2);// 按优先级顺序移除和返回元素while (priorityQueue1.TryDequeue(out var item, out var priority)){Console.WriteLine($"处理 {item} 优先级 {priority}");}// 自定义优先级规则var priorityQueue2 = new PriorityQueue<Task, (int, int)>(new TaskPriorityComparer());// 添加任务priorityQueue2.Enqueue(new Task { Name = "任务A" }, (1, 2));priorityQueue2.Enqueue(new Task { Name = "任务B" }, (1, 1));priorityQueue2.Enqueue(new Task { Name = "任务C" }, (2, 3));// 按优先级顺序处理任务while (priorityQueue2.TryDequeue(out var task, out var priority)){var note = $"执行任务 {task.Name} 紧急程度 {priority.Item1} 重要性 {priority.Item2}";Console.WriteLine(note);Console.WriteLine("是否输入新任务?(Y / N): ");var key = Console.ReadKey(); Console.WriteLine("");if (key.Key == ConsoleKey.Y){Console.WriteLine("请输入任务信息(任务X,1,1):");var taskInfo = Console.ReadLine(); Console.WriteLine("");if (!string.IsNullOrEmpty(taskInfo)){var infos = taskInfo.Split(',');var taskName = infos[0];var urgency = Convert.ToInt32(infos[1]);// 紧急程度var importance = Convert.ToInt32(infos[2]);// 重要性priorityQueue2.Enqueue(new Task { Name = taskName }, (urgency, importance));Console.WriteLine($"插入任务 {taskName} 紧急程度 {urgency} 重要性 {importance}");} } }}} }