0
点赞
收藏
分享

微信扫一扫

[AcWing] 3370. 牛年(C++实现)

天行五煞 2022-03-18 阅读 91
算法c++

[AcWing] 3370. 牛年(C++实现)

1. 题目

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2. 读题(需要重点注意的东西)

思路(哈希表):
读题
Mildred 在 Bessie 出生前的上一个龙年出生 — > Mildred在 Bessie 之前 9 年出生
Gretta 在 Mildred 出生前的上一个猴年出生 — > Gretta 在 Bessie 之前 17 年出生
Elsie 在 Gretta 出生后的下一个牛年出生 — > Elsie 在 Bessie 之前 12 年出生
Paulina 在 Bessie 出生后的下一个狗年出生 — > Paulina 在 Bessie 之后 9 年出生


Bessie出生的年份定为元年,即0
因此知道第二头牛和Bessie的年份差就知道第二头牛的年份是多少;
同理,第三头牛的年份也是确定的…
因此,每一头牛的年份都能够确定。

3. 解法

-----------------------------------------------解法----------------------------------------------

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

unordered_map<string, int> id = {
    {"Ox", 0}, {"Tiger", 1}, {"Rabbit", 2},
    {"Dragon", 3}, {"Snake", 4}, {"Horse", 5}, 
    {"Goat", 6}, {"Monkey", 7}, {"Rooster", 8}, 
    {"Dog", 9}, {"Pig", 10}, {"Rat", 11}
};

int main(){
    // 用哈希表记录每头牛与Bessie相差的年份p
    unordered_map<string,int> p;
    p["Bessie"] = 0;
    
    int n;
    cin >> n;
    while(n--){
        string s[8];
        for(int i = 0;i < 8; i++) cin >> s[i];
        // 在之前出生 减
        if(s[3] == "previous"){
            // 被比较的牛x,待确定年份的牛s[0],年份s[4]
            int x = p[s[7]],y = id[s[4]];
            int r = ((x - y)%12 + 12 ) % 12;
            if(!r) r = 12;
            p[s[0]] = x - r;
        }else{ // 在之后出生 加
            int x = p[s[7]],y = id[s[4]];
            int r = ((y - x)%12 + 12 ) % 12;
            if(!r) r = 12;
            p[s[0]] = x + r;
        }
    }
    cout << abs(p["Elsie"]) << endl;
    return 0;
}

可能存在的问题

4. 可能有帮助的前置习题

5. 所用到的数据结构与算法思想

6. 总结

举报

相关推荐

0 条评论