• 【C/C++】PAT A1025 Ranking/算法笔记


    题目意思大概是输入一堆人的学号,成绩,给出学号,总排名,考场号,考场内排名。
    这是我第一次写的:

    #include <iostream>
    #include <algorithm>
    using namespace std;
    const int maxn = 30005;
    
    struct Student
    {
       int registnum[13];
       int score;
       int rank_in_group;
       int group;
    };
    
    Student stu[maxn]; //创建数组用于存储
    
    bool cmp(Student a, Student b)
    {
       if(a.score != b.score) return a.score > b.score;
       else return a.registnum < b.registnum;
    }
    
    int main()
    {
       //输入
       int n, k, num=0;
       scanf("%d", &n);
       //fflush(stdin);
       for (int i = 1; i <= n; i++) //考场号
       {
          scanf("%d", &k);
          ///fflush(stdin);
          for (int j = 0; j < k; j++)
          {
             scanf("%d%d", &stu[num].registnum, &stu[num].score);
             stu[num].group = i; 
             num++;
          }
          //组内排名
          sort(stu + num - k, stu + num, cmp);
          //组内排号
          stu[num - k].rank_in_group = 1;
          for (int j = 1; j < k; j++)
          {  
             if (stu[num - k + j].score != stu[num - k + j - 1].score)
             {
                stu[num - k + j].rank_in_group = stu[num - k + j - 1].rank_in_group + 1;
             }
             else
             {
                stu[num - k + j].rank_in_group = stu[num - k + j - 1].rank_in_group;
             }
          }
       }
       printf("%d
    ", num); //总人数
       sort(stu, stu + num, cmp);
       int r = 1;
       for (int i = 0; i < num; i++)
       {
          if (i>0 && stu[i].score != stu[i-1].score) //避免出现数组访问问题
          {
             r = i + 1;
          }
          printf("%d %d %d %d
    ", stu[i].registnum, r, stu[i].group, stu[i].rank_in_group);
       }
    
       system("pause");
    }
    

    但是有问题,那个学号总是输入不对。后来一想是因为13位数字的数组,输入的话得一个一个输入(输入到每个位置)。
    但是直接int a[13]然后输入scanf("%d",&a)这样
    肯定只能输入到一个里面
    比如这段测试代码:

    (剩余的奇怪数字是因为没有清内存)
    然而13位的学号,对于单个是int型的数组来说,又超内存了
    int是一种数据类型,在编程语言C中,是用于定义整数类型变量的标识符。在一般的电脑中,int占用4字节,32比特,数据范围为-21474836482147483647[-2^312^31-1]
    然后就把改成了输入字符串数组,因为用scanf("%s",a)的话,他就会自己放进去了

  • 相关阅读:
    [GIT] warning: LF will be replaced by CRLF问题解决方法
    最近想学的工具
    如何在webstrom中配置eslint和less
    Git常用命令
    windows下nginx安装、配置与使用
    关于 addEventListener 和 handleEvent 方法
    PHP中的魔术方法总结 :__construct, __destruct , __call, __callStatic,__get, __set, __isset, __unset , __sleep, __wakeup, __toStr
    Git使用详细教程
    9个永恒的UI设计原则
    常见浏览器兼容性问题与解决方案
  • 原文地址:https://www.cnblogs.com/kinologic/p/14154916.html
Copyright © 2020-2023  润新知