題意:至關於考試排名,若是成績同樣按學號(從小到大),不然按成績從高到低排名。java
思路:略。ios
注:用java寫的超時了(這題時限爲300ms)。說明java比較慢。c++
心得:這題讓我對Java比較器的用法加深了,此外對c++的sort排序也理解了一些。this
#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; }
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); } } }