ECNU 2849 成绩排序

ECNU 2849 成绩排序

链接

https://acm.ecnu.edu.cn/problem/2849

题目

单点时限: 2.0 sec

内存限制: 256 MB

有n (<=100)个学生的成绩记录,其中包含学号和成绩两项。

按照成绩从高到低顺序输出成绩及格( >=60 )学生的学号和成绩。成绩相同时按照学号从小到大顺序输出。

输入格式
第 1 行:输入一个整数n,表示学生记录数。

第 2 行 ~ n+1 行:每行是学号(11 位数字)及成绩(0 到 100 之间的整数)。学号和成绩之间有一个空格。

输出格式
按要求输出结果,每行输出一个空格分隔的学号及成绩。

样例
input
5
10002130201 90
10002130230 80
10002130231 85
10002130148 48
10002130167 90
output
10002130167 90
10002130201 90
10002130231 85
10002130230 80

思路

还行,限制条件一加也就是有点麻烦。
首先建立类,用来排序,字符串存学号,int存成绩,如果不及格,那就把成绩当110分存进去,最后输出不考虑。
然后比较器用来比较,优先分数,高分在前,之后学号,低号在前。但是学号是拿字符串存的,这里就采用一个longcheck函数(随便取的),直接比较第一个不同的字符,小的在前即可。

代码

  public static class Test {

    public String x;
    public int y;

    public Test(String x, int y) {
      this.x = x;
      this.y = y;
    }
  }

  public static int longcheck(String x, String y) {
    StringBuffer sb1 = new StringBuffer(x);
    StringBuffer sb2 = new StringBuffer(y);
    for (int i = 0; i < x.length(); i++) {
      if (sb1.charAt(i) != sb2.charAt(i)) {
        return sb1.charAt(i) - sb2.charAt(i);
      }
    }
    return 1;
  }

  public static void fun() {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    Test[] test = new Test[n];
    int count = 0;
    for (int i = 0; i < n; i++) {
      String num = sc.next();
      int score = sc.nextInt();
      if (score > 59) {
        test[i] = new Test(num, score);
      } else {
        test[i] = new Test("1", 110);
      }
    }

    Arrays.sort(test, new Comparator<Test>() {
      @Override
      public int compare(Test o1, Test o2) {
        if (o1.y != o2.y) {
          return o2.y - o1.y;
        } else {
          return longcheck(o1.x, o2.x);
        }
      }
    });
    for (int i = 0; i < n; i++) {
      if (test[i].y != 110) {
        System.out.println(test[i].x + " " + test[i].y);
      }
    }
  }

原文地址:https://www.cnblogs.com/blogxjc/p/14291806.html