胡凡 《算法笔记》 上机实战训练指南 chap3 入门模拟: 3.2 查找元素

news/2024/11/24 13:24:18/

胡凡 《算法笔记》 上机实战训练指南 chap3 入门模拟: 3.2 查找元素

文章目录

  • 胡凡 《算法笔记》 上机实战训练指南 chap3 入门模拟: 3.2 查找元素
  • 【PAT B1041】考试座位号
  • 【PAT B1004】成绩排名
  • 【PAT B1028】人口普查
    • 解决过程(cpp)
      • AC代码
    • python实现
      • AC代码
        • pycode1
        • pycode2
      • 未AC代码
        • pycode3原因超时
        • pycode4原因还是超时
  • 【PAT A1011】World Cup Betting
    • 梳理一下题意
    • 开始写代码
        • 一次性AC
    • 去看看别人的代码,感觉自己🤣 杀鸡焉用牛刀
  • 【PAT A1006】Sign In and Sign Out
    • AC 还是用前面用到的erase&remove
    • 乐,再次感叹杀鸡焉用牛刀....🤣🤣🤣🤣🤣
      • 书上的做法也值得学习一下
        • 要注意这个问题
        • 一个遗留问题
    • 用python玩玩
      • AC代码1 input()
      • AC代码2 sys
  • 【PAT A1036】Boys VS Girls
    • AC
    • 还是学习一下书上的代码

【PAT B1041】考试座位号

  • 【PAT B1041】考试座位号

  • 难蚌 , long long的输出应该写成%lld ,一开始写成%d 卡了很久

    #include <iostream>
    using namespace std;
    typedef struct student
    {long long examnum;int testnum;int chairnum;
    } stu;
    stu s[1010];
    // stu s[1010];
    int N, M;
    int m[1010];
    int main()
    {int en, tn, cn;cin >> N;for (int i = 1; i <= N; i++){// cin >> en >> tn >> cn;// s[i].examnum = en;// s[i].testnum = tn;// s[i].chairnum = cn;cin >> s[i].examnum >> s[i].testnum >> s[i].chairnum;}cin >> M;for (int i = 1; i <= M; i++){cin >> m[i];for (int j = 1; j <= N; j++){if (m[i] == s[j].testnum){printf("%lld %d\n", s[j].examnum, s[j].chairnum);}}}
    }
    

【PAT B1004】成绩排名

  • 【PAT B1004】成绩排名

  • AC代码

    #include <iostream>
    #include <algorithm>
    using namespace std;
    int n;
    struct Student{char name[12];char num[12];int score;bool operator < (const Student &S)const{return this->score > S.score;}};
    bool max_cmp(Student S1, Student S2)
    {return S1.score > S2.score;
    }
    struct Student s[1000];
    int main()
    {cin >> n;for(int i = 1; i <= n ; i ++ ){cin >> s[i].name >> s[i].num >> s[i].score;}sort(s+1,s+1+n,max_cmp);cout << s[1].name << " " << s[1].num << endl;cout << s[n].name << " " << s[n].num << endl;}
    

【PAT B1028】人口普查

  • 【PAT B1028】人口普查

解决过程(cpp)

  • 首先这个日期我一开始的想法是 作为int的话,怎么拼凑成一个大数呢

    2001/05/12 → 20010512 ,

    过程是2001x1000+05x100+12x1,主要是05这种不好直接搞,或者写if条件,那就有点麻烦了

    于是写到这里的时候我犹豫了

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <algorithm>
    using namespace std;int N;typedef struct Person{char name[5];
    //   string date;  想了想感觉不合理,还得拆分字符串转为数字int year;int month;int day;
    }Person;Person P[100010];
    int valid; //有效生日个数int main()
    {cin >> N;for(int i = 0; i < N; i++){cin >> P[i].name;cin >> P[i].year >> "/" >> P[i].month >> "/" >> P[i].day;}//把出生日看成一个大数字2001/05/12 -> 20010512//今天:20140906//那我不如拼接字符串???return 0;
    }
    

    那我能不能看成字符串,把里面的/去掉,拼凑成字符串"20010512",再转换为数字

    试试这样子:👇

    #include <iostream>
    #include <string>using namespace std;int main() {string date = "2001/05/12";// Replace '/' characters with empty stringsdate.erase(remove(date.begin(), date.end(), '/'), date.end());// Convert the resulting string to a numberint num = stoi(date);cout << num << endl; // 20010512return 0;
    }
  • 于是我一口气写到了这一步

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <string>
    #include <algorithm>
    using namespace std;int N;typedef struct Person{
    //     char name[5];string name;int date;
    }Person;Person P[100010];
    int valid; //有效生日个数int main()
    {cin >> N;string tempdate;string tempName;int dateNumTemp;int index = 0;for(int i = 0; i < N; i++){cin >> tempName;cin >> tempdate;tempdate = tempdate.erase(remove(data.begin(),data.end(),'/'),data.end());dateNumTemp = stoi(tempdate);if(20140906<=dateNumTemp<=22140906){P[index].name = tempName;P[index].date = dateNumTemp;index += 1}}//把出生日看成一个大数字2001/05/12 -> 20010512//今天:20140906//那我不如拼接字符串???for(int j = 0; j < index; j++)cout << indexreturn 0;
    }
    

    突然发现忘记结构体如何使用sort了

  • 想起来之后补充上去

    同时发现了那个错误 tempdate = tempdate.erase(remove(data.begin(),data.end(),'/'),data.end());

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <string>
    #include <algorithm>
    using namespace std;int N;typedef struct Person{
    //     char name[5];string name;int date;
    }Person;Person P[100010];bool cmp(Person a, Person b) {return a.date < b.date;
    }
    int main()
    {cin >> N;string tempdate;string tempName;int dateNumTemp;int index = 0;for(int i = 0; i < N; i++){cin >> tempName;cin >> tempdate;
    //      错误写法...赋值...不需要   tempdate = tempdate.erase(remove(tempdate.begin(),tempdate.end(),'/'),tempdate.end());tempdate.erase(remove(tempdate.begin(),tempdate.end(),'/'),tempdate.end());dateNumTemp = stoi(tempdate);if(20140906<=dateNumTemp && dateNumTemp <=22140906){P[index].name = tempName;P[index].date = dateNumTemp;index += 1;}}sort(P,P+index,cmp);cout << index << P[0].name << P[index-1].name;return 0;
    }
    
    • 突然发现没加空格… cout << index << P[0].name << P[index-1].name

      改了之后,居然还是一个测试样例都没过…

    • 突然发现了一个很大的问题! 这样子作为限定条件的话, 输入的日期可以有13月41号,14月39号这种,

      但这个问题应该不是主要矛盾,先自己测试测试

      不是问题,因为题目里面说了“这里确保每个输入的日期都是合法的”

    • 测试了一下代码,确实是错误地

    image-20230109155137939

    • 然后感觉很奇怪…加了一些测试

      #include <iostream>
      #include <cstdio>
      #include <cstdlib>
      #include <string>
      #include <algorithm>
      using namespace std;int N;typedef struct Person{
      //     char name[5];string name;int date;
      }Person;Person P[100010];bool cmp(Person a, Person b) {return a.date < b.date;
      }
      int main()
      {cin >> N;string tempdate;string tempName;int dateNumTemp;int index = 0;for(int i = 0; i < N; i++){cin >> tempName;cin >> tempdate;        tempdate.erase(remove(tempdate.begin(),tempdate.end(),'/'),tempdate.end());dateNumTemp = stoi(tempdate);printf("%d\n",dateNumTemp); printf("----------\n");if(20140906<=dateNumTemp && dateNumTemp <=22140906){P[index].name = tempName;cout << P[index].name << endl;P[index].date = dateNumTemp;printf("%d\n",P[index].date); index += 1;}}sort(P,P+index,cmp);cout << index << " " << P[0].name << " " << P[index-1].name;return 0;
      }
      

      image-20230109161219785

stoi需要C++11,在vscode里面暂时没有学如何去配置,就先用dev c++来跑了

  • 突然发现,🤣,日期那里搞错咯,应该往前面推两百岁,而不是往未来🤣🤣🤣

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <string>
    #include <algorithm>
    using namespace std;int N;typedef struct Person{
    //     char name[5];string name;int date;
    }Person;Person P[100010];bool cmp(Person a, Person b) {return a.date < b.date;
    }
    int main()
    {cin >> N;string tempdate;string tempName;int dateNumTemp;int index = 0;for(int i = 0; i < N; i++){cin >> tempName;cin >> tempdate;tempdate.erase(remove(tempdate.begin(),tempdate.end(),'/'),tempdate.end());dateNumTemp = stoi(tempdate);if(18140906<=dateNumTemp && dateNumTemp <=20140906){P[index].name = tempName;P[index].date = dateNumTemp;index += 1;}}sort(P,P+index,cmp);cout << index << " " << P[0].name << " " << P[index-1].name;return 0;
    }
    

    这个时候,看起来是对了的

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IOd779Pi-1673287468238)(null)]

    However…

    image-20230109161518124

AC代码

  • 经过大佬指点,知道错的地方在哪了

    • 但是有可能过滤完了合法的人是0个

      image-20230109174118755

      如果全过滤掉了,那么index为0, P[-1].name就错了, P[0].name 没有输入内容

  • AC代码

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <string>
    #include <algorithm>
    using namespace std;int N;typedef struct Person{
    //     char name[5];string name;int date;
    }Person;Person P[100010];bool cmp(Person a, Person b) {return a.date < b.date;
    }
    int main()
    {cin >> N;string tempdate;string tempName;int dateNumTemp;int index = 0;for(int i = 0; i < N; i++){cin >> tempName;cin >> tempdate;tempdate.erase(remove(tempdate.begin(),tempdate.end(),'/'),tempdate.end());dateNumTemp = stoi(tempdate);if(18140906<=dateNumTemp && dateNumTemp <=20140906){P[index].name = tempName;P[index].date = dateNumTemp;index += 1;}}sort(P,P+index,cmp);cout << index << " " << P[0].name << " " << P[index-1].name;return 0;
    }
    

感觉我的比书上的做法更好(

书上是套了好多if else

image-20230109180756162

erase和remove是如何工作的:

remove是改变了元素的顺序,erase才是真的删除

  • C++ 中 remove 与 erase 的理解
  • https://juejin.cn/post/6844903817734160391
  • c++ string的erase删除方法

python实现

AC代码

pycode1

错误代码

import sysN = int(sys.stdin.readline())P = []for i in range(N):temp = sys.stdin.readline().split()tempName = temp[0]tempDate = temp[1]dateNumTemp = int(tempDate.replace('/',''))if 18140906<=dateNumTemp and dateNumTemp <=20140906:P.append([tempName,dateNumTemp])P.sort(key=lambda x:x[1])print(len(P),P[0][0],P[-1][0])
image-20230109162257501

加上len的判断就AC啦

import sysN = int(sys.stdin.readline())P = []for i in range(N):temp = sys.stdin.readline().split()tempName = temp[0]tempDate = temp[1]dateNumTemp = int(tempDate.replace('/',''))if 18140906<=dateNumTemp and dateNumTemp <=20140906:P.append([tempName,dateNumTemp])P.sort(key=lambda x:x[1])
if len(P) == 0:print(0)
else:print(len(P),P[0][0],P[-1][0])

pycode2

这个错误应该是input导致的非零返回

def find_youngest_oldest():# Read N and create a list of Person objectsN = int(input())person_list = []for i in range(N):name = input()birthday = input().replace('/', '')date_num = int(birthday)if 18140906 <= date_num and date_num <= 20140906:person_list.append((name, date_num))# Sort the list by birthdayperson_list.sort(key=lambda x: x[1])# Print the number of valid birthdays, and the name of the youngest and oldest personprint(len(person_list), person_list[0][0], person_list[-1][0])find_youngest_oldest()
image-20230109164611257

下面这个AC了

import sys
def find_youngest_oldest():# Read N and create a list of Person objectsN = int(sys.stdin.readline())person_list = []for i in range(N):name,birthday = sys.stdin.readline().split()
#         name = input()birthday = birthday.replace('/', '')date_num = int(birthday)if 18140906 <= date_num and date_num <= 20140906:person_list.append((name, date_num))# Sort the list by birthdayperson_list.sort(key=lambda x: x[1])if len(person_list)==0:print(0)# Print the number of valid birthdays, and the name of the youngest and oldest personelse:print(len(person_list), person_list[0][0], person_list[-1][0])find_youngest_oldest()
image-20230109220309198

未AC代码

pycode3原因超时

import sys
import datetimeclass Person:def __init__(self, name, birthday):self.name = nameself.birthday = datetime.datetime.strptime(birthday, '%Y/%m/%d')def find_youngest_oldest():# Read N and create a list of Person objectsN = int(sys.stdin.readline())person_list = []for i in range(N):name, birthday = sys.stdin.readline().split()person_list.append(Person(name, birthday))# Sort the list by birthdayperson_list.sort(key=lambda x: x.birthday)# Filter out invalid birthdays (less than 200 years ago or in the future)today = datetime.datetime(2014, 9, 6)two_hundred_years_ago = datetime.datetime(1814, 9, 6)
#     two_hundred_years_ago = today - datetime.timedelta(days=365*200)valid_people = [p for p in person_list if p.birthday < today and p.birthday > two_hundred_years_ago]# Print the number of valid birthdays, and the name of the youngest and oldest personprint(len(valid_people), valid_people[0].name, valid_people[-1].name)# Test the function
find_youngest_oldest()
image-20230109163204438
  • 发现了两个错误,非零返回应该是前面那个len为0时,数组下标越界导致的?…

    于是加上len为0时的分支, 还有个错误就是 应该是闭区间 而不是开区间,改成<=和>=

    valid_people = [p for p in person_list if p.birthday <= today and p.birthday >= two_hundred_years_ago]

    import sys
    import datetimeclass Person:def __init__(self, name, birthday):self.name = nameself.birthday = datetime.datetime.strptime(birthday, '%Y/%m/%d')def find_youngest_oldest():# Read N and create a list of Person objectsN = int(sys.stdin.readline())person_list = []for i in range(N):name, birthday = sys.stdin.readline().split()person_list.append(Person(name, birthday))# Sort the list by birthdayperson_list.sort(key=lambda x: x.birthday)# Filter out invalid birthdays (less than 200 years ago or in the future)today = datetime.datetime(2014, 9, 6)two_hundred_years_ago = datetime.datetime(1814, 9, 6)
    #     two_hundred_years_ago = today - datetime.timedelta(days=365*200)valid_people = [p for p in person_list if p.birthday <= today and p.birthday >= two_hundred_years_ago]# Print the number of valid birthdays, and the name of the youngest and oldest personif len(valid_people)==0:print(0)else:print(len(valid_people), valid_people[0].name, valid_people[-1].name)# Test the function
    find_youngest_oldest()
    image-20230109211542110

    emm, python确实慢,最后一个不知道该咋解决了

    • 类的实例化那一步写成这个也行

              p = Person(name,birthday)person_list.append(p)
      

pycode4原因还是超时

  • 想到了力扣上的一些代码风格

    噢对,如果没有import sys 会显示五个非零返回…

    import datetime
    from collections import deque
    from typing import List
    import sysclass Person:def __init__(self, name: str, birthday: str) -> None:self.name = nameself.birthday = datetime.datetime.strptime(birthday, '%Y/%m/%d')def find_youngest_oldest(N: int, people: List[Person]) -> None:# Sort the list of Person objects by birthday using quicksortpeople.sort(key=lambda x: x.birthday)# Use a deque to store the valid peopletoday = datetime.datetime(2014, 9, 6)two_hundred_years_ago = datetime.datetime(1814, 9, 6)valid_people = deque()# Iterate through the list of people and add the valid ones to the dequefor person in people:if person.birthday <= today and person.birthday >= two_hundred_years_ago:valid_people.append(person)if len(valid_people)==0:print(0)# Print the number of valid birthdays, and the name of the youngest and oldest personelse:print(len(valid_people), valid_people[0].name, valid_people[-1].name)# Test the function
    N = int(sys.stdin.readline())
    people = []
    for i in range(N):name, birthday = sys.stdin.readline().split()people.append(Person(name, birthday))
    find_youngest_oldest(N, people)
    image-20230109214216463

    里面参与比大小的datetime是这种格式的
    1990-01-01 00:00:00
    1980-01-01 00:00:00
    1970-01-01 00:00:00

    • 参考:python3 datetime全解,比大小,做差值运算,转化成月、周、日、年等各种级别的运算

  • 搜了一些
    • OJ python答题结果"返回非零"
    • python非零返回_PTA中提交Python3程序的一些套路
    • PAT 中提交 Python3 的一些注意事项
    • 【python & ACM 输入输出的处理:sys.stdin.readline().strip().split())】
    • python3 牛客网:OJ在线编程常见输入输出练习(ACM模式)

【PAT A1011】World Cup Betting

  • 【PAT A1011】World Cup Betting

梳理一下题意

  • W for win, T for tie, and L for lose.

  • There was an odd assigned to each result. The winner’s odd would be the product of the three odds times 65%.

    For example, 3 games’ odds(概率,投注赔率) are given as the following:

     W    T    L
    1.1  2.5  1.7
    1.2  3.1  1.6
    4.1  1.2  1.1
    

    To obtain the maximum profit, one must buy W for the 3rd game, T for the 2nd game, and T for the 1st game. If each bet takes 2 yuans, then the maximum profit would be (4.1×3.1×2.5×65%−1)×2=39.31 yuans (accurate up to 2 decimal places).


没有完全看懂,大概是从输入的9个数据里面找到3个最大的,然后(3个数的积x65%-1)×(选择到的game的个数)

啊不,再看了一眼,是找出每一行最大的相乘?

第一行最大的是2.5,T

第二行最大的是3.1,T

第三行最大的是4.1,W


啊不不,再看一眼题目,each bet takes 2 yuans , 2不是选择到的game的个数哈哈哈, 所有的都是乘以2

开始写代码

  • 首先是要在这个二维数组里面找到每一行的max element,每行就3个,用max应该比较快,同时还需要知道max element的index,从而知道 是 T W 还是 L

一次性AC

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
using namespace std;const int N = 3;int main()
{double odds[N][N];for(int i = 0; i < N; i++){for(int j = 0; j < N; j++){cin >> odds[i][j];}}double res[N];for(int i = 0; i < N; i++){double* row = odds[i];double max_elm = *max_element(row,row+N);int max_index = distance(row, max_element(row,row+N));res[i]= max_elm;if(max_index==0)cout << "W ";else if(max_index==1)cout << "T ";else if(max_index==2)cout << "L ";}double product = 1.0;for(int i = 0; i < N; i++){product *= res[i];}product = (product*0.65-1)*2;printf("%.2f", product);return 0;
}

关于里面的 max_element() 和 distance()

  • The max_element function returns an iterator to the maximum element in the range [first, last),
  • The distance function calculates the distance between two iterators. In this case, we pass the row of the matrix as the range and get the maximum element and its index in one step.
image-20230109223743282

去看看别人的代码,感觉自己🤣 杀鸡焉用牛刀

  • 参考知乎博主的代码

    【PAT A1011】World Cup Betting - Chilan Yuk的文章 - 知乎 https://zhuanlan.zhihu.com/p/399861108

    #include <iostream>
    #include <algorithm>
    #include <cstdio>
    #include <cstdlib>
    using namespace std;const int N = 3;int main()
    {double pro = 0.65;double a, b, c;for(int i = 0; i < N; i++){cin >> a >> b >> c;if(a>=b && a>=c) {pro *= a; cout << "W ";}else if(b>=a && b>=c){pro *= b;cout << "T ";}else if(c>=a && c>=b){pro *= c;cout << "L ";}}printf("%.2f\n",(pro-1)*2);return 0;
    }
    
  • 不过我那个代码通用性确实强一点哈哈哈哈

  • 书上的代码如下

    #include <iostream>
    #include <algorithm>
    #include <cstdio>
    #include <cstdlib>
    using namespace std;const int N = 3;
    char S[3] = {'W','T','L'};
    int idx;
    int main()
    {double ans = 1.0, tmp, a;for(int i = 0; i < 3; i++){tmp = 0.0;for(int j = 0; j < 3; j++){cin >> a;if(a > tmp){tmp = a;idx = j;}}ans *= tmp;printf("%c ", S[idx]);}printf("%.2f",(ans * 0.65 - 1) * 2);return 0;
    }
    

【PAT A1006】Sign In and Sign Out

  • 【PAT A1006】Sign In and Sign Out

AC 还是用前面用到的erase&remove

  • 代码如下

    #include <iostream>
    #include <algorithm>
    #include <string>
    #include <cstdio>
    #include <cstdlib>
    using namespace std;
    typedef struct Time{string ID;string signIn;string signOut;
    }Time;// 思路:去掉冒号转换为字符串比大小
    // 左边一列最小的就是unlock门的
    // 右边一列最大的就是lock门的int M;
    Time t[100010];
    bool cmp1(Time t1, Time t2)
    {return t1.signIn < t2.signIn;
    }
    bool cmp2(Time t1, Time t2)
    {return t1.signOut > t2.signOut;
    }
    int main()
    {string signInTemp;string signOutTemp;cin >> M;for(int i = 0; i < M; i++){cin >> t[i].ID;cin >> signInTemp;cin >> signOutTemp;signInTemp.erase(remove(signInTemp.begin(),signInTemp.end(),':'),signInTemp.end());signOutTemp.erase(remove(signOutTemp.begin(),signOutTemp.end(),':'),signOutTemp.end());t[i].signIn = signInTemp;t[i].signOut = signOutTemp;}//排序两次? cmp1 按照第一个元素来排序 cmp2 按照第二个元素来排序sort(t,t+M,cmp1);cout << t[0].ID << " ";sort(t,t+M,cmp2);cout << t[0].ID;return 0;
    }
    

    乐,再次感叹杀鸡焉用牛刀…🤣🤣🤣🤣🤣

    • 突然发现,完全没有必要把:去掉,带冒号的字符串也完全可以比较大小

    • 把那两行去掉也能AC

      #include <iostream>
      #include <algorithm>
      #include <string>
      #include <cstdio>
      #include <cstdlib>
      using namespace std;
      typedef struct Time{string ID;string signIn;string signOut;
      }Time;// 思路:去掉冒号转换为字符串比大小
      // 左边一列最小的就是unlock门的
      // 右边一列最大的就是lock门的int M;
      Time t[100010];
      bool cmp1(Time t1, Time t2)
      {return t1.signIn < t2.signIn;
      }
      bool cmp2(Time t1, Time t2)
      {return t1.signOut > t2.signOut;
      }
      int main()
      {string signInTemp;string signOutTemp;cin >> M;for(int i = 0; i < M; i++){cin >> t[i].ID;cin >> signInTemp;cin >> signOutTemp;t[i].signIn = signInTemp;t[i].signOut = signOutTemp;}//排序两次? cmp1 按照第一个元素来排序 cmp2 按照第二个元素来排序sort(t,t+M,cmp1);cout << t[0].ID << " ";sort(t,t+M,cmp2);cout << t[0].ID;return 0;
      }
      

书上的做法也值得学习一下

image-20230110000002121

确实,这样子省空间

#include <iostream>
#include <cstdio>
#include <cstring>using namespace std;struct pNode{char id[20];int hh, mm, ss;}temp, ans1, ans2;bool great(pNode node1,pNode node2)
{if(node1.hh != node2.hh) return node1.hh > node2.hh;if(node1.mm != node2.mm) return node1.mm > node2.mm;return node1.ss > node2.ss;
}int main()
{int n;cin >> n;ans1.hh = 24, ans2.mm = 60, ans1.ss = 60;ans2.hh = 0,  ans2.mm = 0,  ans2.ss = 0;//     string colons = ":";for(int i = 0; i < n; i++){
//         cin >> temp.id >> temp.hh >> ":" >> temp.mm >> ":" >> temp.ss;scanf("%s %d:%d:%d", temp.id, &temp.hh, &temp.mm, &temp.ss);if(great(temp,ans1) == false)ans1 = temp;
//         cin >> temp.id >> temp.hh >> ":" >> temp.mm >> ":" >> temp.ss;scanf("%d:%d:%d",  &temp.hh, &temp.mm, &temp.ss);if(great(temp,ans2)== true)ans2 = temp;}cout << ans1.id << " " << ans2.id;
}

要注意这个问题

cin >> temp.id >> temp.hh >> ":" >> temp.mm >> ":" >> temp.ss;还有string colons=":"; cin >> colons 都是不可以的!

The >> operator is used to extract values from an input stream, such as cin, and store them in variables.

一个遗留问题

承接上文,那么我把冒号也当一个变量读进去

但是不管它可以吗

    string colons;for (int i = 0; i < n; i++){cin >> temp.id;cin >> temp.hh >> colons >> temp.mm >> colons >> temp.ss;//         scanf("%s %d:%d:%d", temp.id, &temp.hh, &temp.mm, &temp.ss);if (great(temp, ans1) == false)ans1 = temp;//         cin >> temp.id >> temp.hh >> ":" >> temp.mm >> ":" >> temp.ss;//         scanf("%d:%d:%d",  &temp.hh, &temp.mm, &temp.ss);cin >> temp.hh >> colons >> temp.mm >> colons >> temp.ss;if (great(temp, ans2) == true)ans2 = temp;}

但是,五个样例都是答案错误,我自己去IDE里面跑也是有问题,但是不知道问题出在哪里…

用python玩玩

中途遇到不少次非零返回,发现很多时候是因为读的个数不对,还有list或者tuple的下标越界了之类的…

AC代码1 input()

# Read the input
m = int(input())
records = []
for i in range(m):line = input().split()id_number = line[0]sign_in_time = line[1]sign_out_time = line[2]records.append((id_number, sign_in_time,sign_out_time))# Sort the records by sign in time
# 默认升序
records.sort(key=lambda x: x[1])
print(records[0][0],end=" ")
records.sort(key=lambda x: x[2],reverse = True)
print(records[0][0])

注意sort默认是升序,要降序则需要加上reverse = True

AC代码2 sys

import sysM = int(sys.stdin.readline())
t = []
for i in range(M):ID,signIn,signOut = sys.stdin.readline().split()t.append((ID,signIn,signOut))t = sorted(t, key=lambda x: x[1])
print(t[0][0], end=' ')t = sorted(t, key=lambda x: x[2], reverse=True)
print(t[0][0])

【PAT A1036】Boys VS Girls

  • 【PAT A1036】Boys VS Girls

AC

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
typedef struct Student
{string name;char gender;string ID;int grade;
} STU;
STU boys[1010]; // 题目没给范围嘤
STU girls[1010];
bool cmp(STU s1, STU s2)
{return s1.grade < s2.grade;
}
int main()
{int N;cin >> N; // 老忘记int numOfBoys = 0;int numOfGirls = 0;string name;char gender;string ID;int grade;for (int i = 0; i < N; i++){cin >> name >> gender >> ID >> grade;//         cin >> s[i].name >> s[i].gender >> s[i].ID >> s[i].grade;if (gender == 'M'){boys[numOfBoys].name = name;boys[numOfBoys].gender = gender;boys[numOfBoys].ID = ID;boys[numOfBoys].grade = grade;numOfBoys++;}else{girls[numOfGirls].name = name;girls[numOfGirls].gender = gender;girls[numOfGirls].ID = ID;girls[numOfGirls].grade = grade;numOfGirls++;}}// cmp是升序sort(boys, boys + numOfBoys, cmp);sort(girls, girls + numOfGirls, cmp);if (numOfGirls == 0)printf("Absent\n");elsecout << girls[numOfGirls - 1].name << " " << girls[numOfGirls - 1].ID << endl;if (numOfBoys == 0)printf("Absent\n");elsecout << boys[0].name << " " << boys[0].ID << endl;if (numOfBoys == 0 || numOfGirls == 0)printf("NA");elsecout << girls[numOfGirls - 1].grade - boys[0].grade;return 0;
}

image-20230110013719440

还是学习一下书上的代码

主要是书上没有开那么大的结构体,没有依赖sort

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
struct Student
{char name[15];char id[15];int score;
}M, F, temp; //M为分数最低的男生 F为分数最高的女生
void init()
{M.score = 101;F.score = -1;
}
int main()
{init();int N;cin >> N; // 老忘记char gender;for (int i = 0; i < N; i++){cin >> temp.name >> gender >> temp.id >> temp.score;if (gender == 'M' && temp.score < M.score){M = temp;}else if(gender == 'F' && temp.score > F.score){F = temp;}}if(F.score == -1)printf("Absent\n"); //没有女生  这个方法好诶,相当于flag没变化就说明没有输入elsecout << F.name <<" " << F.id << endl;if(M.score==101)cout << "Absent" << endl;else cout << M.name <<" "<< M.id << endl;if(F.score == -1 || M.score == 101)cout << "NA";elsecout << F.score - M.score;return 0;
}

http://www.ppmy.cn/news/10846.html

相关文章

如何设置Windows文件夹背景为黑色?(其实就是“深色模式”)

大家好。我们直接进入正题! 如何把Windows文件夹背景改成黑色&#xff1f;就像下面这样。 第一步&#xff1a;打开 “个性化” 设置界面 这里介绍两种方法&#xff1a;(1)在电脑桌面 右键——》 个性化 &#xff0c;如下图 (2)点击 开始——》设置 ——》个性化 &#xff0c;如…

为什么学完了 C 语言觉得自己什么都干不了?

其他方向不了解哈&#xff0c;我2013年大一开始自学C语言&#xff0c;然后就开始做嵌入式&#xff0c;大学四年&#xff0c;到现在毕业又六年&#xff0c;C语言已经陪我十年了&#xff0c;可以说是一直坚持且养家糊口的工具。 所以&#xff0c;别的也许不行&#xff0c;但是嵌…

React源码分析5-commit

前两章讲到了&#xff0c;react 在 render 阶段的 completeUnitWork 执行完毕后&#xff0c;就执行 commitRoot 进入到了 commit 阶段&#xff0c;本章将讲解 commit 阶段执行过程源码。 总览 commit 阶段相比于 render 阶段要简单很多&#xff0c;因为大部分更新的前期操作都…

Google Play Install Referrer API 和 Facebook App Ads Referral 集成

介绍&#xff1a;由于需要精准的获取投放广告的数据&#xff08;投放的平台&#xff0c;防止数据的丢失等&#xff09;。我们使用了Google Play Install Referrer API 和Facebook App Ads Referral结合采集数据&#xff0c;然后通过后台服务记录数据。最后服务器记录的数据与Fa…

【JavaGuide面试总结】Java高级特性基础篇·上

【JavaGuide面试总结】Java高级特性基础篇上1.为什么 Java 中只有值传递&#xff1f;2.static 关键字使用场景3.Exception 和 Error 有什么区别&#xff1f;4.Checked Exception 和 Unchecked Exception 有什么区别&#xff1f;5.Throwable 类常用方法有哪些&#xff1f;6.fina…

MATLAB-一维插值运算

一维插值是指对一维函数进行插值。已知n1个结点(x,y,)&#xff0c;其中x,互不相同(j0&#xff0c;1&#xff0c;2&#xff0c;... n),求任意插值点x*处的插值y*。求解一维插值问题的主要思想是:设结点由未知的函数g(x)产生&#xff0c;函数g(x)为连续函数且g(x)y;(j0,1,...,n);…

一、数据仓库基础理论

数据仓库基础理论一、数据仓库1、概念2、数据仓库分层结构3、为什么要分层二、数据集市三、数据湖1、数据湖和数据仓库一、数据仓库 1、概念 数据仓库&#xff08;Data Warehouse, DW&#xff09;&#xff1a;一个面向主题的、集成的、非易失的、反应历史变化的、用来支持企业…

计算机基础——操作系统

作者简介&#xff1a;一名云计算网络运维人员、每天分享网络与运维的技术与干货。 座右铭&#xff1a;低头赶路&#xff0c;敬事如仪 个人主页&#xff1a;网络豆的主页​​​​​​ 目录 前言 一.操作系统 1.操作系统简介 2.操作系统的主要功能 &#xff08;1&#xff…