程序能力实训 1052 代码 and 一点吐糟

Fifnmar edited 4 年,4 月前

/*/////////////////////////////////////////////////////*/
#include "bits/stdc++.h"

/* PreCondition:
h is a head pointer of a linked-list
PostCondition:
return the head pointer of the sorted linked-list
*/
NODE* SortRationalList(NODE* h) {
    // 一般我特别讨厌 EOJ 上这种固定主程序的题,因为它们的代码一般写的
    // 特别烂,而且连 Markdown 格式都不会用,复制还得自己调。不过这个
    // 还好,代码写得至少能看。

    // 但是能看只是能看,其实还是跟屎一样,只不过消了毒吃不死而已。

    using namespace std;

    struct Fraction {
        int32_t numerator;
        uint32_t denominator;
        bool operator<(Fraction const& frac) const {
            auto lhs = static_cast<int64_t>(numerator)* frac.denominator;
            auto rhs = static_cast<int64_t>(frac.numerator)* denominator;
            if (lhs == rhs) {
                return numerator < frac.numerator;
            } else {
                return lhs < rhs;
            }
        }
        Fraction(string const& num) {
            auto pos = num.find('/');
            if (pos == string::npos) {
                numerator = stol(num);
                denominator = 1;
            } else {
                numerator = stol(num.substr(0, pos));
                denominator = stoul(num.substr(pos + 1));
            }
        }
    };

    struct Frac_node {
        Node* crude_ptr;
        Fraction frac;
        bool operator<(Frac_node const rhs) const {
            // Frac_node is small enough to be copied instead of referenced.
            return frac < rhs.frac;
        }
    };

    vector<Frac_node> node_table;
    for (Node* iter = h; iter != nullptr; iter = iter->next) {
        node_table.push_back({ iter, { iter->value } });
    }
    node_table.push_back({ nullptr, {"0"} }); // sentinel.

    sort(node_table.begin(), node_table.end() - 1);

    for (size_t sz = node_table.size() - 1, i = 0; i != sz; ++i) {
        node_table[i].crude_ptr->next = node_table[i + 1].crude_ptr;
    }
    return node_table.front().crude_ptr;
}

Comments