PAT甲级——1097 Deduplication on a Linked List——分数 25

题目


解法1

点击查看代码
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <vector>

using namespace std;

struct Node {
    int key;
    string next;
};

int main() {
    string head;
    int n;
    cin >> head >> n;

    unordered_map<string, Node> nodeMap;
    for (int i = 0; i < n; i++) {
        string addr, nextAddr;
        int key;
        cin >> addr >> key >> nextAddr;
        nodeMap[addr] = {key, nextAddr};
    }

    unordered_set<int> seenKeys;
    vector<pair<string, Node>> uniqueList, removedList;
    
    string curr = head;
    while (curr != "-1") {
        int absKey = abs(nodeMap[curr].key);
        if (seenKeys.count(absKey)) {
            removedList.push_back({curr, nodeMap[curr]});
        } else {
            seenKeys.insert(absKey);
            uniqueList.push_back({curr, nodeMap[curr]});
        }
        curr = nodeMap[curr].next;
    }

    // 输出去重后的链表
    for (int i = 0; i < uniqueList.size(); i++) {
        cout << uniqueList[i].first << " " << uniqueList[i].second.key << " ";
        if (i == uniqueList.size() - 1)
            cout << "-1\n";
        else
            cout << uniqueList[i + 1].first << "\n";
    }

    // 输出删除的链表
    for (int i = 0; i < removedList.size(); i++) {
        cout << removedList[i].first << " " << removedList[i].second.key << " ";
        if (i == removedList.size() - 1)
            cout << "-1\n";
        else
            cout << removedList[i + 1].first << "\n";
    }

    return 0;
}

posted on 2025-03-20 10:09  LEESOL-cn  阅读(4)  评论(0)    收藏  举报

导航