1. 程式人生 > >生日相同(結構體排序)

生日相同(結構體排序)

Description
在一個有180人的大班級中,存在兩個人生日相同的概率非常大,現給出每個學生的學號,出生月日。試找出所有生日相同的學生。

Input
第一行為整數n,表示有n個學生,n<100。 
此後每行包含一個字串和兩個整數,分別表示學生的學號(字串長度小於10)和出生月(1<=m<=12)日(1<=d<=31)。 
學號、月、日之間用一個空格分隔。

Output
對每組生日相同的學生,輸出一行, 
其中前兩個數字表示月和日,後面跟著所有在當天出生的學生的學號,數字、學號之間都用一個空格分隔。 
對所有的輸出,要求按日期從前到後的順序輸出。 
對生日相同的學號,按輸入的順序輸出。

Sample Input
6
00508192 3 2
00508153 4 5
00508172 3 2
00508023 4 5
00509122 4 5
00232323 7 7

Sample Output
3 2 00508192 00508172
4 5 00508153 00508023 00509122

Hint
沒有生日相同的不輸出!

解題思路:
一看到跟學生資訊有關的題,第一個想到的就是用結構體,無非是一些跟學號,班級,姓名,成績有關的題目。果然這題也不例外,就是把學生資訊儲存在結構體中,對結構體排個序,遍歷一遍,輸出生日相同的學生學號。
AC程式碼:

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
struct student
{
    char id[15];
    int month, date;
    int xu;          // 記錄學生的輸入順序,因為題中提到對生日相同的學生,按輸入順序輸出
};
bool cmp(student a,student b)
{
    if(a.month == b.month )
    {
        if(a.date == b.date)
        {
            return a.xu < b.xu ;
        }
        else
        {
            return a.date < b.date ;  // 按題目要求進行結構體排序
        }
    }
    return a.month < b.month ;
}
 
int main()
{
    student stu[105];
    int n;
    bool isBegin = true, isFirst = true;
    scanf("%d", &n);
    for(int i = 0; i < n; i++)
    {
        scanf("%s %d %d", &stu[i].id, &stu[i].month, &stu[i].date);
        stu[i].xu = i ;
    }
    sort(stu, stu+n, cmp);
    for(int i = 0; i < n-1; i++)
    {
        if(stu[i].month == stu[i+1].month && stu[i].date == stu[i+1].date)
        {
            if(isBegin)
            {
                if(isFirst)
                {
                    printf("%d %d %s", stu[i].month, stu[i].date, stu[i].id);   // 先輸出生日,第一組輸出不需要換行
                    isFirst = false;
                }
                else
                printf("\n%d %d %s",stu[i].month,stu[i].date,stu[i].id);   // 之後每組輸出得先換行,並且都先輸出生日
                isBegin = false;
            }
            printf(" %s",stu[i+1].id);   // 之後跟的是輸出學生學號
        }
        else
            isBegin = true;
    }
    return 0;
}


--------------------- 
作者:userluoxuan 
來源:CSDN 
原文:https://blog.csdn.net/userluoxuan/article/details/37671995 
版權宣告:本文為博主原創文章,轉載請附上博文連結!