hdu 5427 A problem of sorting

来源:互联网 发布:淘宝运营商是真的吗 编辑:程序博客网 时间:2024/06/05 08:20

题目链接:<a target=_blank href="http://acm.hdu.edu.cn/showproblem.php?pid=5427">点击打开链接</a>

题意:题目就是给出人的名字和出生年,并且不会有两个人是同一年,让按照每个人年龄从小到大输出对应的名字。


题解:这个题目有个难点就是名字的输入可能有空格,最后输出的时候得把空格都输出,所以在输入的时候要将名字和出生年当成一个字符串一起输入,然后把字符串的后面4位

存在结构体的data中,进行比较,最后对应输出名字。

输入的时候要用cin.getline(s,210) 字符串及其长度,还有提前加getchar();

注意结构体使用,sort中cmp的使用,以及字符串s后面加结束符。

代码:

#include <iostream>#include <cstdio>#include <cmath>#include <cstring>#include <algorithm>using namespace std;struct people{    char name[110];    int data;};struct people a[110];int cmp(people b,people c){    return b.data>c.data;}char s[210];int main(){    int t,n,len;    cin>>t;    while(t--)    {        cin>>n;        getchar();        for(int i=0;i<n;i++)        {            cin.getline(s,210);            len=strlen(s);            a[i].data=1000*s[len-4]+100*s[len-3]+10*s[len-2]+s[len-1];            len-=5;            s[len]='\0';            strcpy(a[i].name,s);        }        sort(a,a+n,cmp);        for(int i=0;i<n;i++)            cout<<a[i].name<<endl;    }    return 0;}


害羞

0 0