天天看點

1025.PAT RankingPAT Ranking

PAT Ranking

解答:

思路:用結構體來存放資料,用tmp容器來存放臨時學生資料,用sort算法來對成績進行排序,再給這些臨時學生資料賦排名,昨晚排名操作後将臨時資料全部插入到最終學生結構體數組中即可。

注意同等成績排名相同的排名方法:

for(int j=1;j<K;j++){
            if(tmp[j].Score==tmp[j-1].Score) tmp[j].location_rank=tmp[j-1].location_rank;
                else tmp[j].location_rank=j+1;
        }
           

最後對所有學生成績排名,獲得總成績排名,并賦給final_rank

#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
map<string,int> Map;
struct Competitor{
    string Id;
    int Score;
    int final_rank;
    int location_number;
    int location_rank;
};
bool comp(Competitor c1,Competitor c2){
    //如果分數不等,按分數從大到小排序,如果分數相同,按從小到達學号排序
    return c1.Score!=c2.Score ? c1.Score>c2.Score : c1.Id<c2.Id;
}

int main(){
    int N,K;
    cin>>N;
    vector<Competitor> ans;
    for(int i=1;i<=N;i++){
        cin>>K;
        vector<Competitor> tmp(K);
        for(int j=0;j<K;j++){
            cin>>tmp[j].Id>>tmp[j].Score;
            tmp[j].location_number=i;
        }
        sort(tmp.begin(),tmp.end(),comp);
        tmp[0].location_rank=1;
        ans.push_back(tmp[0]);
        for(int j=1;j<K;j++){
            if(tmp[j].Score==tmp[j-1].Score) tmp[j].location_rank=tmp[j-1].location_rank;
                else tmp[j].location_rank=j+1;
            ans.push_back(tmp[j]);
        }
    }
    sort(ans.begin(),ans.end(),comp);
    ans[0].final_rank=1;
    for(int j=1;j<ans.size();j++){
            if(ans[j].Score==ans[j-1].Score) ans[j].final_rank=ans[j-1].final_rank;
                else ans[j].final_rank=j+1;
        }
    
    cout<<ans.size()<<endl;
    for(int i=0;i<ans.size();i++){
        cout<<ans[i].Id<<' '<<ans[i].final_rank<<' '<<ans[i].location_number<<' '<<ans[i].location_rank<<endl;
    }
    
    return 0;
}
           

繼續閱讀