1.题目描述—请见链接
2.思路解析
此题有比较复杂的比较策略:
输出第一行首先给出达到最低分数线的考生人数 M,随后 M 行,每行按照输入格式输出一位考生的信息,考生按输入中说明的规则从高到低排序。当某类考生中有多人总分相同时,按其德分降序排列;若德分也并列,则按准考证号的升序输出。
考虑使用c#用于对象比较的两个接口:IComparable和IComparer
IComparable | IComparer |
---|---|
在要比较的对象的类中实现,可以比较该对象和另外一个对象 | 在一个单独的类中实现,可以比较任意两个对象 |
提供了CompareTo()方法,该方法只接受当前类的对象 | 提供了Compare()方法,接受两个对象,返回一个整型结果 |
使用:person1.CompareTo(person2) | myCompare.Compare(person1,person2),也可作为集合sort()方法的参数 |
此题中要对集合中的所有元素进行排序,所以选择创建一个自定义类MyCompare实现IComparer接口,代码如下:
/// <summary>
/// 比较排序,return y-x 表示降序排列,return x-y 表示升序排列
/// </summary>
/// <param name="x">参数1</param>
/// <param name="y">参数2</param>
/// <returns></returns>
public int Compare(Student x, Student y)
{
if (x.TotalScore != y.TotalScore)
// 按TotalScore字段进行降序排列
return y.TotalScore - x.TotalScore;
else if (x.De != y.De)
// 按De字段进行降序排列
return y.De - x.De;
else
// 按Num字段进行升序排列
return x.Num - y.Num;
}
然后可以将MyCompare类的对象当作Sort()方法的参数,实现对集合list的排序:
List<Student> list = new List<Student>();
list.Sort(new MyCompare());
除去排序的代码,其余代码主要实现将对应的学生信息放入对应的集合中即可。
3.代码
using System;
using System.Collections.Generic;
namespace 德才论
{
public struct Student
{
public int Num;
public int De;
public int Cai;
}
class Program
{
static void Main(string[] args)
{
{
string[] str = Console.ReadLine().Split();
int stuNum = int.Parse(str[0]);
// l取最低分数线,即德分和才分均不低于 L 的考生才有资格被考虑录取
int l = int.Parse(str[1]);
// h为优先录取线——德分和才分均不低于此线的被定义为“才德全尽”
int h = int.Parse(str[2]);
int count = stuNum;
List<List<Student>> list = new List<List<Student>>();
list.Add(new List<Student>());
list.Add(new List<Student>());
list.Add(new List<Student>());
list.Add(new List<Student>());
for (int i = 0; i < stuNum; i++)
{
string[] stuInfo = Console.ReadLine().Split();
Student s;
s.Num = int.Parse(stuInfo[0]);
s.De = int.Parse(stuInfo[1]);
s.Cai = int.Parse(stuInfo[2]);
if (s.De < l || s.Cai < l)
{
count--;
}
else if (s.De >= h && s.Cai >= h)
{
list[0].Add(s);
}
else if (s.Cai < h && s.De >= h)
{
list[1].Add(s);
}
else if (s.De < h && s.Cai < h && s.De >= s.Cai)
{
list[2].Add(s);
}
else
{
list[3].Add(s);
}
}
Console.WriteLine(count);
for (int i = 0; i < list.Count; i++)
{
list[i].Sort(new MyCompare());
for (int j = 0; j < list[i].Count; j++)
{
if (i != 0 || j != 0) Console.WriteLine();
Console.Write(list[i][j].Num + " " + list[i][j].De + " " + list[i][j].Cai);
}
}
}
}
}
public class MyCompare : IComparer<Student>
{
public int Compare(Student x, Student y)
{
if (x.De + x.Cai != y.De + y.Cai)
return (y.De + y.Cai) - (x.De + x.Cai);
else if (x.De != y.De)
return y.De - x.De;
else
return x.Num - y.Num;
}
}
}
4.总结
1、掌握两个用于集合排序的接口的使用情况;
2、注意比较逻辑的写法:
每类考生按总分降序排列,当某类考生中有多人总分相同时,按其德分降序排列;若德分也并列,则按准考证号的升序输出。
先写总分不同的情况下的处理逻辑,然后写德分不同的情况下的处理逻辑,最后写准考证号不同的处理逻辑。
if (x.De + x.Cai != y.De + y.Cai)
return (y.De + y.Cai) - (x.De + x.Cai);
else if (x.De != y.De)
return y.De - x.De;
else
return x.Num - y.Num;
3、最后此代码未能完全通过测试,其中有两个测试点超时,相同思路的c++代码未超时,由此可将语言越低级运行速度越快。