C++笔记(1)——Anniversary

世界太喧闹,不如敲代码。

直接上题目:


Zhejiang University is about to celebrate her 122th anniversary in 2019. To prepare for the celebration, the alumni association (校友会) has gathered the ID's of all her alumni. Now your job is to write a program to count the number of alumni among all the people who come to the celebration.

Input Specification:
Each input file contains one test case. For each case, the first part is about the information of all the alumni. Given in the first line is a positive integer N (≤10的5次方 ). Then N lines follow, each contains an ID number of an alumnus. An ID number is a string of 18 digits or the letter X. It is guaranteed that all the ID's are distinct.

The next part gives the information of all the people who come to the celebration. Again given in the first line is a positive integer M (≤10的5次方 ). Then M lines follow, each contains an ID number of a guest. It is guaranteed that all the ID's are distinct.

Output Specification:
First print in a line the number of alumni among all the people who come to the celebration. Then in the second line, print the ID of the oldest alumnus -- notice that the 7th - 14th digits of the ID gives one's birth date. If no alumnus comes, output the ID of the oldest guest instead. It is guaranteed that such an alumnus or guest is unique.

Sample Input:
5
372928196906118710
610481197806202213
440684198612150417
13072819571002001X
150702193604190912
6
530125197901260019
150702193604190912
220221196701020034
610481197806202213
440684198612150417
370205198709275042

Sample Output:
3
150702193604190912


说白了就是给两组名单,一组是来访校友,一组是真正来了的嘉宾,要求输出最老的来访校友的ID,如果没有校友那么输出最老嘉宾的名单,同时还要输出来访的校友的总人数。

代码:

#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;

bool cmp(string a, string b) {
    return a.substr(6, 8) < b.substr(6, 8); // 就是直接比较字符串大小,因为ASCII里面越大的数字反而对应的数字越小,例如'1984' < '1998'  
}

int main() {
    string name;
    int a_num, g_num;
    unordered_map<string, bool> find_alu;
    vector<string> all_guest, alu_list;
    cin >> a_num;
    for (int i = 0; i < a_num; ++i) {
        cin >> name;
        find_alu[name] = true;              // 建立映射map,string -> bool,用来判定一个ID是不是属于校友列表的 
    }
    cin >> g_num;
    for (int i = 0; i < g_num; ++i) {
        cin >> name;
        all_guest.push_back(name);
        if (find_alu[name]) alu_list.push_back(name);  // 如果是校友那么就把ID添加到校友名单中 
    }
    printf("%d\n", alu_list.size());
    if (!alu_list.empty()) {
        sort(alu_list.begin(), alu_list.end(), cmp);    // 用STL的方法来进行排序 
        printf("%s\n", alu_list[0].c_str());
    }
    else {
        sort(all_guest.begin(), all_guest.end(), cmp);
        printf("%s\n", all_guest[0].c_str());
    }
    return 0;
}

这里的代码依旧是和上一篇一样,作者是merely尘埃,我稍微改动了下。

猜你喜欢

转载自www.cnblogs.com/yejianying/p/cpp_notes_1.html
今日推荐