题意及思路
题意:相当于考试排名,如果成绩一样按学号(从小到大),否则按成绩从高到低排名。
思路:略。
注:用java写的超时了(这题时限为300ms)。说明java比较慢。
心得:这题让我对Java比较器的用法加深了,此外对c++的sort排序也理解了一些。
代码(C++)
#include<bits/stdc++.h> using namespace std; typedef struct{ char id[15]; int score; int location_number; int local_rank; }Stu; const int MAXSIZE = 30010; Stu stus[MAXSIZE]; bool cmp(Stu a,Stu b){ if(a.score!=b.score) return a.score>b.score; //按成绩排 else return strcmp(a.id,b.id)<0; //按id排 } int main() { std::ios::sync_with_stdio(false); cin.tie(0); int n,k,total; // total:总人数 cin >> n; for(int i=1;i<=n;i++){ cin >> k; for(int j=0;j<k;j++){ cin >> stus[total].id >> stus[total].score; stus[total].location_number = i; total++; } sort(stus+total-k,stus+total-k+k,cmp); //设置local_rank stus[total-k].local_rank = 1; //将该考场的第一名的本场排名置为1 for(int j=total-k+1;j<total;j++){ if(stus[j].score == stus[j-1].score){ stus[j].local_rank = stus[j-1].local_rank; }else{ stus[j].local_rank = j-(total-k) + 1; //下标减去首地址,再+1 } } } cout << total << endl; sort(stus,stus+total,cmp); //设置rank-总排名 int rank = 1; for(int i=0;i<total;i++){ if(i>0 && stus[i].score!=stus[i-1].score){ rank = i+1; //当考试的成绩与上一个同学的成绩不相同时,置其rank为当前总人数 } printf("%s ",stus[i].id); printf("%d %d %d\n",rank,stus[i].location_number,stus[i].local_rank); } return 0; }
代码(Java)
package com.pta.java; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class A1025 { private static ArrayList<acmer> li = new ArrayList<>(); private static ArrayList<acmer> mi = new ArrayList<>(); public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); for (int i = 1; i <= n; i++) { int k = in.nextInt(); for (int j = 1; j <= k; j++) { String registration_number = in.next(); int score = in.nextInt(); acmer a = new acmer(); a.registration_number = registration_number; a.score = score; a.location_number = i; mi.add(a); } // sort Collections.sort(mi); // set local_rank mi.get(0).local_rank = 1; for (int j = 1; j < k; j++) { if (mi.get(j).score == mi.get(j - 1).score) { mi.get(j).local_rank = mi.get(j - 1).local_rank; } else { mi.get(j).local_rank = j + 1; } } li.addAll(mi); mi.clear(); } // sort all Collections.sort(li); int len = li.size(); System.out.println(len); // set final_rank int rank = 1; for (int i = 0; i < len; i++) { acmer a = li.get(i); if (i > 0 && a.score != li.get(i - 1).score) { rank = i + 1; } System.out.print(a.registration_number + " "); System.out.println(rank + " " + a.location_number + " " + a.local_rank); } in.close(); } } class acmer implements Comparable<acmer> { String registration_number; int location_number; int local_rank; int score; public int compareTo(acmer o) { if (this.score == o.score) { return this.registration_number.compareTo(o.registration_number); } else { return -(this.score - o.score); } } }