1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| #include <iostream> #include <utility> #include <vector> #include <list> #include <ostream> #include <sstream> #include <unordered_map>
using namespace std;
struct LinkList { int val_; LinkList *next_;
explicit LinkList(int val, LinkList *next = nullptr) : val_(val), next_(next) {} };
LinkList *buildLink(unordered_map<std::string, pair<int, std::string >> &mp, std::string &start) { auto len = mp.size(); LinkList *link = nullptr; LinkList *re = nullptr; for (int i = 0; i < len; ++i) { auto &[val, end] = mp[start]; start = end; auto link_node = new LinkList(val, nullptr); if (link == nullptr) { link = link_node; re = link; } else { link->next_ = link_node; link = link->next_; } } return re; }
int findMiddle(LinkList *head, int len) { int middle = len / 2; auto tmp = head; for (int i = 0; i < middle; ++i) { tmp = tmp->next_; } return tmp->val_; }
void clear(LinkList *head) { while (head != nullptr) { auto tmp = head->next_; head->next_ = nullptr; delete head; head = tmp; } }
int main() { std::string startAddr; int num;
std::string data; getline(cin, data); istringstream iss(data); iss >> startAddr >> num;
unordered_map<std::string, pair<int, std::string >> map_; for (int i = 0; i < num; ++i) { getline(cin, data); istringstream iss2(data); std::string start, end; int val; iss2 >> start >> val >> end; map_[start] = make_pair(val, end); }
auto link = buildLink(map_, startAddr);
cout << findMiddle(link, num) << endl;
clear(link);
return 0; }
|