hdu 2093 考试排名(sscanf)

来源:互联网 发布:java工厂模式例子 编辑:程序博客网 时间:2024/05/14 23:22

模拟题。

直接从教程里拉解析。

因为表格里的数据格式不统一。有时候有"()",有时候又没有。而它也不会给我们提示。

这种情况下,就只能它它们统一看作字符串来处理了。现在就请出我们的主角sscanf()!

sscanf
语法:

#include int sscanf( const char *buffer, const char *format, ... );

函数sscanf()和scanf()类似, 只是输入从buffer(缓冲区)中读取.
比如:sscanf("1 2 3", "%d%d%d", &a, &b, &c);
则a = 1, b = 2, c = 3;

只要输入表格内容后,用格式化输入"%d(%d)",然后判断输入结果,如果是2,表示带有括号,如果是1,则没有括号。
排序直接用快速排序就可以了。规则已经说的很清楚了。


代码:

#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;const int MaxN = 1000;struct student{    char name[11];    int sum;    int total;    /*bool operator<(const student &a)const    {        if(a.total != total)            return a.total > total;        else if(a.sum != sum)            return a.sum < sum;        else            return strcmp(a.name, name);    }*/} stu[MaxN];/*int cmp(const void *va, const void *vb){    student *a, *b;    a = (student*)va;    b = (student*)vb;    if(a->total != b->total)        return a->total - b->total;    else if(b->sum != a->sum)        return b->sum - a->sum;    else        return strcmp(b->name, a->name);}*/int cmp(const void *a, const void *b){    if ((*(student *)a).total != (*(student *)b).total)        return (*(student *)a).total - (*(student *)b).total;    else if ((*(student *)b).sum != (*(student *)a).sum)        return (*(student *)b).sum - (*(student *)a).sum;    else        return strcmp((*(student *)b).name, (*(student *)a).name);}int main(){    //freopen("in.txt", "r", stdin);    int n, m;    int i, j;    scanf("%d%d", &n, &m);    for(i = 0; scanf("%s", stu[i].name)!=EOF; i++)    {        for(j = 0; j < n; j++)        {            char style[10];            int t, f;            scanf("%s", style);            int res = sscanf(style, "%d(%d)", &t, &f);            if(res == 2)            {                stu[i].total++;                stu[i].sum += t + f * m;            }            else if(res == 1 && t > 0)            {                stu[i].total++;                stu[i].sum += t;            }        }    }    qsort(stu, i, sizeof(student), cmp);    for(i--; i >= 0; i--)        printf("%-10s %2d %4d\n", stu[i].name, stu[i].total, stu[i].sum);    return 0;}


0 0
原创粉丝点击