为什么对了
2026-03-06 17:48:03
发布于:上海
#include <algorithm>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <locale>
#include <map>
#include <memory>
#include <mutex>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <string>
#include <thread>
#include <tuple>
#include <type_traits>
#include <typeinfo>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include <array>
#include <bitset>
#include <condition_variable>
#include <list>
#include <ratio>
#include <system_error>
#include <typeindex>
#include <valarray>
#define ENABLE_VERBOSE_LOGGING 1
#define ENABLE_TIMING 1
#define ENABLE_THREAD_SAFETY 1
#define USE_MULTITHREADING 0
#define MAX_ITERATIONS 1
#define ENABLE_INPUT_SANITIZATION 1
#define ENABLE_RESULT_CACHING 1
#define ENABLE_PERFORMANCE_COUNTERS 1
#define MAX_INPUT_LENGTH 1024
#define CACHE_CAPACITY 1000
#define MAX_THREADS 4
#define START_OF_PROGRAM do {
#define END_OF_PROGRAM } while(0)
#define BEGIN_NAMESPACE namespace {
#define END_NAMESPACE }
#define UNUSED(x) ((void)(x))
#define IGNORE_RETURN_VALUE(x) if (x) {}
#define LIKELY(x) (__builtin_expect(!!(x), 1))
#define UNLIKELY(x) (__builtin_expect(!!(x), 0))
#define PROGRAM_NAME "A+B Solver"
#define PROGRAM_VERSION "9.9.9"
#define PROGRAM_AUTHOR "Developer"
#define PROGRAM_LICENSE "MIT"
const char* const prog_name = PROGRAM_NAME;
const char* const prog_version = PROGRAM_VERSION;
const char* const prog_author = PROGRAM_AUTHOR;
const char* const prog_license = PROGRAM_LICENSE;
const double pi = 3.14159265358979323846;
const double euler = 2.71828182845904523536;
const double golden_ratio = 1.61803398874989484820;
const float zero_f = 0.0f;
const int magic_num = 42;
const char greet_msg[] = "Welcome to A+B solver!\n";
const char bye_msg[] = "Thank you for using this program.\n";
static bool initialized = false;
static std::mutex global_mutex;
static int log_level = 0;
using integer = int;
using input_pair = std::pair<integer, integer>;
using result_type = integer;
using clock_type = std::chrono::high_resolution_clock;
using time_point = clock_type::time_point;
using duration_ms = std::chrono::duration<double, std::milli>;
enum class error_code : int {
success = 0,
invalid_input = 1,
division_by_zero = 2,
out_of_memory = 3,
unknown_error = 99
};
enum class add_strategy : uint8_t {
simple,
bitwise,
template_meta,
multithreaded,
recursive,
functional,
count
};
struct math_const {
static constexpr double pi = 3.141592653589793;
static constexpr double e = 2.718281828459045;
static constexpr double phi = 1.618033988749895;
static constexpr int max_int = std::numeric_limits<int>::max();
static constexpr int min_int = std::numeric_limits<int>::min();
};
enum class weekday {
mon, tue, wed, thu, fri, sat, sun
};
enum class month {
jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec
};
enum class color {
red, green, blue, yellow, cyan, magenta, black, white
};
struct point2d { double x, y; };
struct point3d { double x, y, z; };
struct segment { point2d s, e; };
namespace core {
namespace arithmetic {
namespace detail {
template<typename T>
struct is_int : std::false_type {};
template<> struct is_int<char> : std::true_type {};
template<> struct is_int<signed char> : std::true_type {};
template<> struct is_int<unsigned char> : std::true_type {};
template<> struct is_int<short> : std::true_type {};
template<> struct is_int<unsigned short> : std::true_type {};
template<> struct is_int<int> : std::true_type {};
template<> struct is_int<unsigned int> : std::true_type {};
template<> struct is_int<long> : std::true_type {};
template<> struct is_int<unsigned long> : std::true_type {};
template<> struct is_int<long long> : std::true_type {};
template<> struct is_int<unsigned long long> : std::true_type {};
}
class add_algorithm {
public:
virtual ~add_algorithm() = default;
virtual result_type run(integer a, integer b) const = 0;
virtual std::string label() const = 0;
};
class direct_add : public add_algorithm {
public:
result_type run(integer a, integer b) const override {
return a + b;
}
std::string label() const override { return "direct"; }
};
class bit_add : public add_algorithm {
public:
result_type run(integer a, integer b) const override {
while (b != 0) {
integer carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
std::string label() const override { return "bitwise"; }
};
class recursive_add : public add_algorithm {
private:
result_type calc(integer a, integer b) const {
if (b == 0) return a;
if (b > 0) return calc(a + 1, b - 1);
return calc(a - 1, b + 1);
}
public:
result_type run(integer a, integer b) const override {
return calc(a, b);
}
std::string label() const override { return "recursive"; }
};
class thread_add : public add_algorithm {
private:
mutable std::mutex mtx;
mutable result_type res;
mutable bool done;
void work(integer a, integer b) const {
result_type val = a + b;
std::lock_guard<std::mutex> lock(mtx);
res = val;
done = true;
}
public:
thread_add() : res(0), done(false) {}
result_type run(integer a, integer b) const override {
done = false;
std::thread t(&thread_add::work, this, a, b);
t.join();
return res;
}
std::string label() const override { return "threaded"; }
};
template<int A, int B>
struct constexpr_adder {
static constexpr int value = A + B;
};
class constexpr_add : public add_algorithm {
public:
result_type run(integer a, integer b) const override {
return a + b;
}
std::string label() const override { return "constexpr"; }
};
}
class calculator {
private:
std::unique_ptr<arithmetic::add_algorithm> algo;
mutable std::mutex mtx;
public:
explicit calculator(arithmetic::add_algorithm* a) : algo(a) {
if (!algo) throw std::invalid_argument("null algorithm");
}
calculator(const calculator&) = delete;
calculator(calculator&&) noexcept = default;
~calculator() = default;
calculator& operator=(const calculator&) = delete;
calculator& operator=(calculator&&) noexcept = default;
result_type add(integer a, integer b) const {
std::lock_guard<std::mutex> lock(mtx);
return algo->run(a, b);
}
void set_algo(arithmetic::add_algorithm* a) {
if (!a) throw std::invalid_argument("null algorithm");
algo.reset(a);
}
};
namespace input {
class reader {
public:
virtual ~reader() = default;
virtual std::string get_line() = 0;
virtual bool valid() const = 0;
};
class console_reader : public reader {
private:
std::istream& in;
public:
explicit console_reader(std::istream& is = std::cin) : in(is) {}
std::string get_line() override {
std::string line;
std::getline(in, line);
return line;
}
bool valid() const override {
return in.good();
}
};
class fixed_reader : public reader {
private:
std::string line;
bool ok;
public:
explicit fixed_reader(const std::string& s) : line(s), ok(true) {}
std::string get_line() override {
ok = false;
return line;
}
bool valid() const override {
return ok;
}
};
}
namespace parse {
class parser {
public:
virtual ~parser() = default;
virtual input_pair parse(const std::string& s) = 0;
};
class space_parser : public parser {
public:
input_pair parse(const std::string& s) override {
std::istringstream iss(s);
integer a, b;
if (!(iss >> a >> b)) throw std::invalid_argument("parse failed");
return {a, b};
}
};
template<char D = ' '>
class delim_parser : public parser {
public:
input_pair parse(const std::string& s) override {
std::stringstream ss(s);
std::string t;
std::vector<std::string> vec;
while (std::getline(ss, t, D)) {
if (!t.empty()) vec.push_back(t);
}
if (vec.size() != 2) throw std::invalid_argument("need two numbers");
integer a = std::stoi(vec[0]);
integer b = std::stoi(vec[1]);
return {a, b};
}
};
}
namespace check {
class checker {
public:
virtual ~checker() = default;
virtual bool good(const input_pair& p) const = 0;
virtual std::string msg() const = 0;
};
class range_check : public checker {
private:
mutable std::string err;
public:
bool good(const input_pair& p) const override {
if (p.first < math_const::min_int || p.first > math_const::max_int) {
err = "first out of range";
return false;
}
if (p.second < math_const::min_int || p.second > math_const::max_int) {
err = "second out of range";
return false;
}
return true;
}
std::string msg() const override { return err; }
};
class positive_check : public checker {
private:
mutable std::string err;
public:
bool good(const input_pair& p) const override {
if (p.first < 0) { err = "first negative"; return false; }
if (p.second < 0) { err = "second negative"; return false; }
return true;
}
std::string msg() const override { return err; }
};
class multi_check : public checker {
private:
std::vector<std::unique_ptr<checker>> list;
mutable std::string err;
public:
void add(checker* c) {
list.emplace_back(c);
}
bool good(const input_pair& p) const override {
for (const auto& x : list) {
if (!x->good(p)) {
err = x->msg();
return false;
}
}
return true;
}
std::string msg() const override { return err; }
};
}
namespace output {
class formatter {
public:
virtual ~formatter() = default;
virtual std::string build(result_type r) const = 0;
};
class plain_formatter : public formatter {
public:
std::string build(result_type r) const override {
return std::to_string(r);
}
};
class json_formatter : public formatter {
public:
std::string build(result_type r) const override {
std::ostringstream oss;
oss << "{\"result\":" << r << "}";
return oss.str();
}
};
class xml_formatter : public formatter {
public:
std::string build(result_type r) const override {
std::ostringstream oss;
oss << "<result>" << r << "</result>";
return oss.str();
}
};
}
namespace log {
enum class level {
debug, info, warn, err
};
class logger {
private:
level threshold;
std::ostream& out;
public:
explicit logger(level l = level::info, std::ostream& os = std::cerr)
: threshold(l), out(os) {}
template<typename... Args>
void write(level l, const Args&... args) const {
if (l >= threshold) {
std::lock_guard<std::mutex> lock(global_mutex);
(out << ... << args) << '\n';
}
}
};
static logger log_main(level::debug, std::cerr);
#define log_dbg(...) log_main.write(level::debug, "[D] ", __VA_ARGS__)
#define log_inf(...) log_main.write(level::info, "[I] ", __VA_ARGS__)
#define log_wrn(...) log_main.write(level::warn, "[W] ", __VA_ARGS__)
#define log_err(...) log_main.write(level::err, "[E] ", __VA_ARGS__)
}
namespace util {
void empty() {}
int rand_int(int l, int r) {
static std::random_device rd;
static std::mt19937 gen(rd());
std::uniform_int_distribution<> d(l, r);
return d(gen);
}
void banner() {
std::cerr << "========== A+B SOLVER ==========\n";
}
}
class app {
private:
std::unique_ptr<input::reader> r;
std::unique_ptr<parse::parser> p;
std::unique_ptr<check::checker> c;
std::unique_ptr<calculator> calc;
std::unique_ptr<output::formatter> f;
time_point t_start, t_end;
public:
app(std::unique_ptr<input::reader> r_,
std::unique_ptr<parse::parser> p_,
std::unique_ptr<check::checker> c_,
std::unique_ptr<calculator> calc_,
std::unique_ptr<output::formatter> f_)
: r(std::move(r_)), p(std::move(p_)), c(std::move(c_)),
calc(std::move(calc_)), f(std::move(f_)) {}
~app() = default;
int run() {
int a, b;
UNUSED(a); UNUSED(b);
t_start = clock_type::now();
log_inf("read input");
std::string line = r->get_line();
log_inf("parse");
input_pair nums;
try {
nums = p->parse(line);
} catch (...) {
log_err("parse failed");
return (int)error_code::invalid_input;
}
log_inf("check");
if (!c->good(nums)) {
log_err("check failed: ", c->msg());
return (int)error_code::invalid_input;
}
log_inf("calculate");
result_type res = calc->add(nums.first, nums.second);
log_inf("format");
std::string out = f->build(res);
t_end = clock_type::now();
duration_ms dur = t_end - t_start;
log_inf("time: ", dur.count(), "ms");
std::cout << out << '\n';
return (int)error_code::success;
}
};
}
}
namespace {
struct init {
init() { std::cerr << "init\n"; }
~init() { std::cerr << "cleanup\n"; }
} global_init;
struct static_data {
int val;
static_data() : val(42) {}
} data;
int dummy[1000] = {0};
}
template<int N>
constexpr int sum() {
return N + sum<N-1>();
}
template<>
constexpr int sum<0>() { return 0; }
static_assert(sum<5>() == 15, "sum 5");
template<typename... Ts>
struct type_list {};
using sample_types = type_list<int, double, char, float, long>;
int main() {
using namespace core;
using namespace core::log;
util::banner();
std::cerr << greet_msg;
std::cerr << "Program: " << prog_name << " " << prog_version << "\n";
std::cerr << "Author: " << prog_author << "\n";
std::cerr << "License: " << prog_license << "\n";
auto r = std::make_unique<input::console_reader>();
auto p = std::make_unique<parse::space_parser>();
auto chk = std::make_unique<check::multi_check>();
chk->add(new check::range_check());
auto c = std::move(chk);
int s = util::rand_int(0, 4);
std::unique_ptr<arithmetic::add_algorithm> algo;
switch (s) {
case 0: algo = std::make_unique<arithmetic::direct_add>(); break;
case 1: algo = std::make_unique<arithmetic::bit_add>(); break;
case 2: algo = std::make_unique<arithmetic::constexpr_add>(); break;
case 3: algo = std::make_unique<arithmetic::thread_add>(); break;
case 4: algo = std::make_unique<arithmetic::recursive_add>(); break;
default: algo = std::make_unique<arithmetic::direct_add>(); break;
}
auto calc = std::make_unique<calculator>(algo.release());
auto fmt = std::make_unique<output::plain_formatter>();
app instance(std::move(r), std::move(p), std::move(c),
std::move(calc), std::move(fmt));
int ec = instance.run();
std::cerr << bye_msg;
return ec;
}



全部评论 1
傻福
1周前 来自 上海
0























有帮助,赞一个