EOJ 97. 邮件地址排序

单点时限: 2.0 sec
内存限制: 256 MB

现接收到一大批电子邮件,邮件地址格式为:用户名@主机域名,要求把这些电子邮件地址做主机域名的字典序升序排序,如果主机域名相同,则做用户名的字典序降序排序。

输入格式
第一行输入一个正整数 n,表示共有 n 个电子邮件地址需要排序。
接下来 n 行,每行输入一个电子邮件地址(保证所有电子邮件地址的长度总和不超过 10^6)。

· 对于 50% 的数据,保证 n⩽100,|si|⩽100。

用户名只包含字母数字和下划线,主机域名只包含字母数字和点。

输出格式
按排序后的结果输出 n 行,每行一个电子邮件地址。

样例

input
8
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
output
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

思路
就是中规中矩普普通通的排序题,唯一的难点就是数据量,最多的样例输入的数据量好像是三十万。
是刚接触编程写的题目,那时候只学了C语言,感觉没法写,感觉很苦恼,不过看了一些动态内存分配,还是磕磕绊绊写完了,现在看来还是有点价值的。
用结构体分开存两部分,然后用qsort函数排序。

ac代码

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

struct Address
{
    char* user, *main;
};

int cmp(const void *a,const void *b)
{
    struct Address x,y;
    x=*((struct Address *)a);
    y=*((struct Address *)b);
    if(strcmp(x.main,y.main)==0) return strcmp(y.user,x.user);
    return strcmp(x.main,y.main);
}

int main()
{
    long long int n,count=0;
    scanf("%lld",&n);
    getchar();
    struct Address *ip=NULL;
    while(count<n)
    {
        long long int counts=0;
        char ch;
        char* temp=NULL;
        char* tempuser=NULL;
        char* tempmain=NULL;
        do
        {
            ch=getchar();
            counts++;
            temp=(char*)realloc(temp, sizeof(char)*(counts+1));
            temp[counts-1]=ch;
        }while(ch!='\n');
        temp[counts]='\0';
        count++;
        ip=(struct Address *)realloc(ip,n*sizeof(struct Address));
        ip[count-1].user=NULL;
        ip[count-1].main=NULL;
        long long int i,j,len=strlen(temp);
        for(i=0;temp[i]!='@';i++)
        {
            tempuser=(char *)realloc(tempuser,sizeof(char)*(i+1));
            tempuser[i]=temp[i];
        }
        tempuser=(char *)realloc(tempuser,sizeof(char)*(i+2));
        tempuser[i]='\0';
        i++;
        for(j=0;i<len;i++,j++)
        {
            tempmain=(char *)realloc(tempmain,sizeof(char)*(j+1));
            tempmain[j]=temp[i];
        }
        tempmain=(char *)realloc(tempmain,sizeof(char)*(j+2));
        tempmain[j]='\0';
        ip[count-1].user=(char *)realloc(ip[count-1].user,
                         sizeof(char)*(strlen(tempuser) + 1));
        ip[count-1].main=(char *)realloc(ip[count-1].main,
                         sizeof(char)*(strlen(tempmain) + 1));
        strcpy(ip[count-1].user,tempuser);
        strcpy(ip[count-1].main,tempmain);
        free(tempuser);
        free(tempmain);
        free(temp);
    }
    qsort(ip,n,sizeof(ip[0]),cmp);
    int j;
    for(j=0;j<n;j++)
    {
        printf("%s@%s",ip[j].user,ip[j].main);
    }
    free(ip);
    return 0;
}
原创文章 9 获赞 10 访问量 664

猜你喜欢

转载自blog.csdn.net/qq_45401156/article/details/105604714
今日推荐