1012 The Best Rank (25 分)(排序,sort用法)

本文介绍了一个学生排名系统的设计与实现,该系统针对计算机科学专业一年级学生的成绩进行评估,通过比较四类排名(C语言编程、数学、英语及平均成绩),确定每位学生的最佳排名,并按优先级顺序输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

To evaluate the performance of our first year CS majored students, we consider their grades of three courses only: C - C Programming Language, M - Mathematics (Calculus or Linear Algrbra), and E - English. At the mean time, we encourage students by emphasizing on their best ranks -- that is, among the four ranks with respect to the three courses and the average grade, we print the best rank for each student.

For example, The grades of C, M, E and A - Average of 4 students are given as the following:

StudentID  C  M  E  A

310101     98 85 88 90

310102     70 95 88 84

310103     82 87 94 88

310104     91 91 91 91

Then the best ranks for all the students are No.1 since the 1st one has done the best in C Programming Language, while the 2nd one in Mathematics, the 3rd one in English, and the last one in average.

Input Specification:

Each input file contains one test case. Each case starts with a line containing 2 numbers N and M (≤2000), which are the total number of students, and the number of students who would check their ranks, respectively. Then N lines follow, each contains a student ID which is a string of 6 digits, followed by the three integer grades (in the range of [0, 100]) of that student in the order of C, M and E. Then there are M lines, each containing a student ID.

Output Specification:

For each of the M students, print in one line the best rank for him/her, and the symbol of the corresponding rank, separated by a space.

The priorities of the ranking methods are ordered as A > C > M > E. Hence if there are two or more ways for a student to obtain the same best rank, output the one with the highest priority.

If a student is not on the grading list, simply output N/A.

Sample Input:

5 6

310101 98 85 88

310102 70 95 88

310103 82 87 94

310104 91 91 91

310105 85 90 90

310101

310102

310103

310104

310105

999999

Sample Output:

1 C

1 M

1 E

1 A

3 A

N/A

本人尝试N小时,一直WA,最后参考柳神代码方可AC。

#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <string>
#include <cctype>
#include <string.h>
#include <cstdio>
using namespace std;
struct node{
    int id,best;
    int score[4],rank[4];
}stu[2005];
int exist[1000000],flag=-1;
bool cmp(node a,node b){
    return a.score[flag]>b.score[flag];
}
int main(){
    int n,m,id;
    scanf("%d %d",&n,&m);
    for(int i=0;i<n;i++){
        scanf("%d %d %d %d",&stu[i].id,&stu[i].score[1],&stu[i].score[2],&stu[i].score[3]);
        stu[i].score[0]=(stu[i].score[1]+stu[i].score[2]+stu[i].score[3])/3.0+0.5;//四舍五入
    }
    for(flag=0;flag<=3;flag++){
        sort(stu,stu+n,cmp);
        stu[0].rank[flag]=1;
        for(int i=1;i<n;i++){
            stu[i].rank[flag]=i+1;
            if(stu[i].score[flag]==stu[i-1].score[flag])
                stu[i].rank[flag]=stu[i-1].rank[flag];
        }
    }
    for(int i=0;i<n;i++){
        exist[stu[i].id]=i+1;//便于最后查找学生id
        stu[i].best=0;
        int minn=stu[i].rank[0];
        for(int j=0;j<=3;j++){
            if(stu[i].rank[j]<minn){
                minn=stu[i].rank[j];
                stu[i].best=j;
            }
        }
    }
    char c[5]={'A','C','M','E'};
    for(int i=0;i<m;i++){
        scanf("%d",&id);
        int temp=exist[id];
        if(temp){
            int best=stu[temp-1].best;
            printf("%d %c\n",stu[temp-1].rank[best],c[best]);
        }else{
            printf("N/A\n");
        }
    }
    return 0;
}







附上sort用法

<think>我们使用GridSearchCV进行参数调优时,可以通过设置`return_train_score=True`来获取每个参数组合在训练集和测试集上的评,然后通过`cv_results_`属性获取详细结果。以下是具体步骤: 1. **初始化GridSearchCV**:设置`return_train_score=True`以便返回所有训练和验证数。 2. **拟合模型**:调用`fit`方法进行参数搜索。 3. **提取结果**:使用`cv_results_`属性获取所有结果,并将其转换为DataFrame以便析。 4. **结果析**:对结果进行排序、筛选和可视化。 ### 代码实现 ```python from sklearn.model_selection import GridSearchCV from sklearn.ensemble import RandomForestRegressor import pandas as pd # 假设已有训练数据 X_train, y_train # 定义参数网格 param_grid = { 'n_estimators': [100, 200, 300], 'max_depth': [10, 20, None], 'min_samples_split': [2, 5, 10], 'max_features': ['sqrt', 0.5, 0.8] } # 创建GridSearchCV对象,设置return_train_score=True grid_search = GridSearchCV( estimator=RandomForestRegressor(random_state=42), param_grid=param_grid, scoring='neg_mean_squared_error', # 回归任务常用负均方误差 cv=5, # 5折交叉验证 n_jobs=-1, # 使用所有CPU核心并行计算 return_train_score=True, # 关键:返回训练数和验证数 verbose=3 # 输出详细过程 ) # 执行网格搜索 grid_search.fit(X_train, y_train) # 将结果转换为DataFrame results_df = pd.DataFrame(grid_search.cv_results_) # 选择需要的列,例如参数组合和评 columns_to_keep = [ 'params', 'mean_test_score', 'std_test_score', 'mean_train_score', 'std_train_score', 'rank_test_score' ] results_df = results_df[columns_to_keep] # 按测试集性能排序 results_df = results_df.sort_values(by='rank_test_score') # 打印前10个参数组合 print(results_df.head(10)) ``` ### 结果解释 - `params`: 参数字典,包含当前组合的参数设置。 - `mean_test_score`: 交叉验证中测试集的平均得(注意:这里得是负均方误差,所以实际MSE需要取负号)。 - `std_test_score`: 测试集得的标准差。 - `mean_train_score`: 训练集的平均得。 - `std_train_score`: 训练集得的标准差。 - `rank_test_score`: 基于测试集得的排名(1表示最好)。 ### 结果可视化 我们可以通过绘制图表来对比不同参数组合的性能: ```python import matplotlib.pyplot as plt import seaborn as sns # 将负MSE转换为正MSE results_df['test_mse'] = -results_df['mean_test_score'] results_df['train_mse'] = -results_df['mean_train_score'] # 绘制前20个最佳参数组合的测试MSE和训练MSE top_results = results_df.head(20).copy() top_results['param_str'] = top_results['params'].astype(str) plt.figure(figsize=(12, 8)) sns.scatterplot( data=top_results, x='test_mse', y='train_mse', hue='param_str', s=100, legend=True ) plt.xlabel('Test MSE') plt.ylabel('Train MSE') plt.title('Comparison of Train and Test MSE for Top Parameter Combinations') plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.tight_layout() plt.savefig('param_comparison.png', dpi=300) ``` ### 输出到文件 将完整结果保存到CSV文件,以便进一步析: ```python results_df.to_csv('grid_search_results.csv', index=False) ``` ### 注意事项 1. **评指标**:回归任务常用`neg_mean_squared_error`(负均方误差),类任务常用`accuracy`等。可通过`scoring`参数设置。 2. **内存消耗**:当参数组合很多时,`return_train_score=True`会显著增加内存消耗,因为需要存储所有训练集和测试集的数。 3. **并行计算**:`n_jobs=-1`使用所有CPU核心加速计算。 ### 引用说明 在参数调优过程中使用并行计算可以显著提升效率[^2],而GridSearchCV提供了完整的参数组合评估结果[^1][^3]。 --- ### 相关问题 1. 如何解释GridSearchCV结果中的标准差? 2. 当参数组合过多时,如何减少GridSearchCV的内存消耗? 3. 除了MSE,还有哪些回归任务常用的评估指标? 4. 如何根据GridSearchCV的结果选择最终模型? 5. 在参数调优中,如何处理过拟合现象?</think>### 使用 GridSearchCV 输出每个参数组合评值的方法 在 Scikit-learn 的 GridSearchCV 中,可以通过以下步骤输出每个参数组合的评值并进行对比析: #### 1. 配置 GridSearchCV 输出所有结果 ```python from sklearn.model_selection import GridSearchCV from sklearn.ensemble import RandomForestRegressor import pandas as pd # 配置关键参数 grid_search = GridSearchCV( estimator=RandomForestRegressor(), param_grid=param_grid, scoring='neg_mean_squared_error', # 回归任务常用负均方误差 cv=5, n_jobs=-1, # 使用所有CPU核心并行计算[^2] return_train_score=True, # ★关键参数:返回所有训练和验证数 verbose=2 # 显示详细过程 ) # 执行参数搜索 grid_search.fit(X_train, y_train) # 提取所有结果到DataFrame results_df = pd.DataFrame(grid_search.cv_results_) ``` #### 2. 提取关键评列 ```python # 筛选关键列 key_columns = [ 'params', 'mean_test_score', 'std_test_score', 'mean_train_score', 'rank_test_score' ] # 创建评对比表 comparison_df = results_df[key_columns].copy() # 转换负MSE为正MSE(更易理解) comparison_df['test_mse'] = -comparison_df['mean_test_score'] comparison_df['train_mse'] = -comparison_df['mean_train_score'] # 按性能排序 comparison_df = comparison_df.sort_values('rank_test_score') ``` #### 3. 输出评对比结果 ```python # 打印所有参数组合评 print("参数组合评对比:") print(comparison_df[['params', 'test_mse', 'train_mse', 'rank_test_score']].head(20)) # 保存到CSV comparison_df.to_csv('parameter_scores_comparison.csv', index=False) ``` #### 4. 结果可视化析 ```python import matplotlib.pyplot as plt import seaborn as sns # 创建参数组合标识 comparison_df['param_id'] = ['组合_'+str(i) for i in range(1, len(comparison_df)+1)] plt.figure(figsize=(12, 6)) sns.lineplot( data=comparison_df, x='param_id', y='test_mse', marker='o', label='验证集MSE' ) sns.lineplot( data=comparison_df, x='param_id', y='train_mse', marker='X', label='训练集MSE' ) plt.xticks(rotation=45) plt.title('参数组合性能对比') plt.ylabel('MSE') plt.xlabel('参数组合') plt.legend() plt.tight_layout() plt.savefig('parameter_scores_comparison.png', dpi=300) ``` #### 5. 关键参数说明 - `return_train_score=True`:强制返回所有训练集评 - `cv_results_`:包含所有结果的字典结构 - 主要评列: - `mean_test_score`:交叉验证平均得 - `std_test_score`:得标准差 - `mean_train_score`:训练集平均得 - `rank_test_score`:性能排名 #### 输出示例: ``` 参数组合评对比: params test_mse train_mse rank_test_score 组合_1 {'max_depth': 20, 'min_samples_split': 2... 0.782 0.065 1 组合_2 {'max_depth': None, 'min_samples_split': 5... 0.815 0.058 2 组合_3 {'max_depth': 10, 'min_samples_split': 10... 0.841 0.072 3 ... ``` ### 技术要点解析 1. **评转换**:负均方误差 → 正均方误差 $$ \text{MSE} = -\text{neg_mean_squared_error} $$ 2. **过拟合检测**:比较训练/验证集MSE差距 $$ \text{过拟合度} = \text{train_mse} - \text{test_mse} $$ 3. **参数重要性析**:计算参数变化对数的影响 $$ \text{敏感度} = \frac{\Delta \text{MSE}}{\Delta \text{参数值}} $$ 4. **并行计算优化**:`n_jobs=-1` 利用所有CPU核心加速计算[^2] ### 相关问题 1. 如何解释 GridSearchCV 结果中的标准差指标? 2. 当参数组合过多时,如何优化结果的可视化展示? 3. 除了 MSE,还有哪些回归任务可用的评指标? 4. 如何根据评结果识别过拟合参数组合? 5. 在参数调优中,训练集评和验证集评的差异说明了什么?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小火汁猛猛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值