前言
刚学习java,就想着在oj做题上时也用java,顺便熟悉一下java的语法。最近学到集合,突然想起之前在scnu oj上做过的一道多级排序的题。于是就动手用java写了一遍。
题目
代码
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeSet;
//2016 201620050 Whengcheng 3.33
public class Main
{
public static class Student implements Comparable<Student>
{
int grade;
long num;
String name;
double score; //由于只是比较,没有运算,并不会出现精度丢失的问题
public Student() {}
public Student(int grade, long num, String name, double score)
{
this.grade = grade;
this.num = num;
this.name = name;
this.score = score;
}
@Override
public String toString()
{
DecimalFormat df=new DecimalFormat("0.00");
return grade+" "+num+" "+name+" "+df.format(score);
}
@Override
public int compareTo(Student stu)
{
int flag1=Integer.compare(grade, stu.grade);
if(flag1!=0) //年级不同
return flag1;
else //年级相同
{
int flag2=Double.compare(score, stu.score);
if(flag2!=0) //成绩不同
return -flag2; //成绩降序
else //成绩相同
return Long.compare(num, stu.num);
}
}
}
public static void main(String[] args)
{
TreeSet<Student> set=new TreeSet<>();
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for(int i=0;i<n;i++)
{
int grade=sc.nextInt();
long num=sc.nextLong();
String name=sc.next();
double score=sc.nextDouble();
Student stu=new Main.Student(grade, num, name, score);
set.add(stu);
}
Iterator<Student> it=set.iterator();
while(it.hasNext())
System.out.println(it.next());
}
}
备注
对比一下C/C++和Java的时间。。。