【九度OJ】1187:最小年齡的3個職工

地址:
http://ac.jobdu.com/problem.php?pid=1187
題目描述:
職工有職工號,姓名,年齡.輸入n個職工的信息,找出3個年齡最小的職工打印出來。
輸入:
輸入第一行包括1個整數N,1<=N<=30,代表輸入數據的個數。
接下來的N行有N個職工的信息:
包括職工號(整數), 姓名(字符串,長度不超過10), 年齡(1<=age<=100)。
輸出:
可能有多組測試數據,對於每組數據,
輸出結果行數爲N和3的較小值,分別爲年齡最小的職工的信息。
關鍵字順序:年齡>工號>姓名,從小到大。
樣例輸入:
5
501 Jack 6
102 Nathon 100
599 Lily 79
923 Lucy 15
814 Mickle 65
樣例輸出:
501 Jack 6
923 Lucy 15
814 Mickle 65
來源:
2003-2005年華中科技大學計算機研究生機試真題

解題思路:
直接用c++的sort庫函數

源碼:

#include<stdio.h>
#include<string.h>
#include<algorithm>

using namespace std;

int n;
struct StaffNode{
    int staffID;
    char staffName[ 15 ];
    int staffAge;
}staff[ 35 ];

bool cmp( StaffNode staff1, StaffNode staff2 ){
    if( staff1.staffAge != staff2.staffAge ){   //如果年齡不相等,按照年齡排序
        return staff1.staffAge  < staff2.staffAge;
    }
    else if( staff1.staffID != staff2.staffID ){
        return staff1.staffID  < staff2.staffID;
    }

    int temp = strcmp( staff1.staffName, staff2.staffName );
    if( temp != 0){
        return temp < 0;
    }
}

int main(){
    while( scanf( "%d", &n ) != EOF ){
        for( int i = 0; i < n; i ++ ){
            scanf( "%d %s %d", &staff[ i ].staffID, &staff[ i ].staffName, &staff[ i ].staffAge );
        }

        sort( staff, staff + n, cmp );

        if( n < 3 ){
            for( int i = 0; i < n; i ++ ){
                printf( "%d %s %d\n", staff[ i ].staffID, staff[ i ].staffName, staff[ i ].staffAge );
            }
        }
        else{
            for( int i = 0; i < 3; i ++ ){
                printf( "%d %s %d\n", staff[ i ].staffID, staff[ i ].staffName, staff[ i ].staffAge );
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章