社区讨论
玄关(72tps求调)
P11186三目运算参与者 1已保存回复 0
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 0 条
- 当前快照
- 1 份
- 快照标识符
- @mhj0ipsz
- 此快照首次捕获于
- 2025/11/03 18:44 4 个月前
- 此快照最后确认于
- 2025/11/03 18:44 4 个月前
CPP
#include <iostream>
#include <string>
#include <vector>
#include <thread>
#include <mutex>
#include <atomic>
#include <sstream>
struct Node {
virtual int evaluate(int x) const = 0;
virtual ~Node() {}
};
struct ConstantNode : Node {
int value;
ConstantNode(int v) : value(v) {}
int evaluate(int x) const override { return value; }
};
struct ConditionalNode : Node {
Node* left;
Node* right;
int threshold;
bool isGreater;
ConditionalNode(int t, bool gt, Node* l, Node* r)
: threshold(t), isGreater(gt), left(l), right(r) {}
~ConditionalNode() {
delete left;
delete right;
}
int evaluate(int x) const override {
return (isGreater ? (x > threshold) : (x < threshold))
? left->evaluate(x) : right->evaluate(x);
}
};
class ParallelEvaluator {
public:
void addTask(int x) {
std::lock_guard<std::mutex> lock(mtx);
tasks.push_back(x);
}
void startEvaluation(Node* root, int threadCount) {
std::vector<std::thread> threads;
for (int i = 0; i < threadCount; ++i) {
threads.emplace_back([this, root]() {
while (true) {
int x;
{
std::lock_guard<std::mutex> lock(mtx);
if (nextTask >= tasks.size()) break;
x = tasks[nextTask++];
}
int result = root->evaluate(x);
{
std::lock_guard<std::mutex> lock(mtx);
results.push_back(result);
}
}
});
}
for (auto& t : threads) {
t.join();
}
}
const std::vector<int>& getResults() const {
return results;
}
private:
std::vector<int> tasks;
std::vector<int> results;
std::mutex mtx;
std::atomic<size_t> nextTask{0};
};
Node* parseExpression(const std::string& expr, int& pos) {
if (isdigit(expr[pos])) {
int num = 0;
while (pos < expr.size() && isdigit(expr[pos])) {
num = num * 10 + (expr[pos++] - '0');
}
return new ConstantNode(num);
}
if (expr[pos] == 'x') {
pos++;
char op = expr[pos++];
if (op == '>' || op == '<') {
int threshold = 0;
while (pos < expr.size() && isdigit(expr[pos])) {
threshold = threshold * 10 + (expr[pos++] - '0');
}
pos++;
Node* left = parseExpression(expr, pos);
pos++;
Node* right = parseExpression(expr, pos);
return new ConditionalNode(threshold, op == '>', left, right);
}
}
return nullptr;
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int m, q;
std::cin >> m >> q;
std::string S;
std::cin >> S;
int pos = 0;
Node* root = parseExpression(S, pos);
ParallelEvaluator evaluator;
std::vector<int> queries(q);
for (int i = 0; i < q; ++i) {
std::cin >> queries[i];
evaluator.addTask(queries[i]);
}
int threadCount = std::min(4, static_cast<int>(std::thread::hardware_concurrency()));
evaluator.startEvaluation(root, threadCount);
for (int result : evaluator.getResults()) {
std::cout << result << '\n';
}
delete root;
return 0;
}
回复
共 0 条回复,欢迎继续交流。
正在加载回复...