您的位置:首页 > 其它

[2012校赛新生组]稳定排序的题目

2014-03-23 15:29 330 查看
题目:ACM比赛都会产生一个最终排名,排名按照题数多少来决定。但是现在,有太多的队伍参与,手动计算排名已经不能满足比赛的需求。现在有一份名单记录各个队伍的ID和做出的题目数,你能不能写一个程序,产生最终的排名。排名要求做出题目数量多的队伍排在前面,如果题数相等,保持输入时的相对顺序不要改变。

思路:就是一般的排序,不过要注意顺序不改变(稳定排序)。

解法一:归并排序

import java.util.*;

public class Main{

public static void main(String[] args){
Main ma = new Main();
ma.go();
}
void go(){
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
while(T-->0){
int n = scan.nextInt();
Troop[] tro = new Troop
;
for(int i=0;i<n;i++)
{
tro[i] = new Troop();
tro[i].ID=scan.nextInt();
tro[i].M=scan.nextInt();
}
mergeSort(tro);
for(int i=0;i<n;i++)
System.out.println(tro[i].ID+" "+tro[i].M);
}

}
public static void mergeSort (Troop[] list)//先分开
{
if (list.length >1)
{
Troop[] fh = new Troop[list.length/2];
System.arraycopy(list, 0, fh, 0, list.length/2);
mergeSort(fh);
Troop[] sh = new Troop[list.length - fh.length];
System.arraycopy(list, list.length/2, sh, 0, list.length-fh.length);
mergeSort(sh);

Troop[] temp = merge(fh,sh);
System.arraycopy(temp , 0 , list , 0 , temp.length);
}
}

private static Troop[] merge(Troop[] list1,Troop[] list2)//然后并到一起去
{
Troop[] temp = new Troop[list1.length+list2.length];
int c1 = 0;
int c2 = 0;
int c3 = 0;

while (c1<list1.length && c2 < list2.length){
if (list1[c1].M>=list2[c2].M)
temp[c3++]=list1[c1++];
else
temp[c3++]=list2[c2++];
}

while(c1<list1.length)
temp[c3++] = list1 [c1++];
while(c2<list2.length)
temp[c3++] = list2 [c2++];

return temp;
}

class Troop{
int ID;
int M;
}
}


解法二:sort排序(重写方法)//来自某小伙伴ww...

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class Main
{
static Scanner scan=new Scanner(System.in);

public static class sort{int id,m;}

public static void main(String[] args)
{
int t=scan.nextInt();
while(t-->0)
{
int n=scan.nextInt();
sort a[]=new sort
;
for(int i=0;i<n;i++)
{
a[i]=new sort();
a[i].id=scan.nextInt();
a[i].m=scan.nextInt();
}
Arrays.sort(a, new Comparator<sort>() {
public int compare(sort a, sort b)
{
if(a.m!=b.m)
return (a.m<b.m?1:-1);
return 0;
}
});
for(int i=0;i<n;i++)
System.out.println(a[i].id+" "+a[i].m);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: