题目数据生成器便携版
为了更好地生成题目的数据,我写了这个题目数据生成器,用于快速生成多组数据,并包含多种文件类型的版本。
注意事项:
当前文件夹下需要有两个 exe 文件 gen.exe 和 std.exe (如果没有会尝试编译 cpp 文件) ,分别是单组数据生成器和标程。把生成器拷贝到此文件夹下,运行即可。
需要输入题目名称(英文名,如: problem ),然后输入需要生成的数据组数。生成后打开当前文件夹下,会多出一个文件夹,名字是你刚才设置的名字,里面包含了所有的数据。打包成 zip 上传即可。
不同平台通用的 C++ 代码。
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <filesystem>
#include <chrono>
#include <thread>
#include <atomic>
#include <cstdlib>
#include <cstdio>
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/wait.h>
#include <unistd.h>
#endif
namespace fs = std::filesystem;
// 跨平台执行命令并获取输出
bool execute_command(const std::string& command, const std::string& input_file,
const std::string& output_file, bool redirect_input = true) {
#ifdef _WIN32
// Windows: 使用 CreateProcess
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = nullptr;
sa.bInheritHandle = TRUE;
HANDLE hStdIn = INVALID_HANDLE_VALUE;
HANDLE hStdOut = INVALID_HANDLE_VALUE;
if (redirect_input && !input_file.empty()) {
hStdIn = CreateFileA(input_file.c_str(), GENERIC_READ, FILE_SHARE_READ,
&sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hStdIn == INVALID_HANDLE_VALUE) {
std::cerr << "Failed to open input file: " << input_file << std::endl;
return false;
}
}
if (!output_file.empty()) {
hStdOut = CreateFileA(output_file.c_str(), GENERIC_WRITE, 0,
&sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hStdOut == INVALID_HANDLE_VALUE) {
std::cerr << "Failed to create output file: " << output_file << std::endl;
if (hStdIn != INVALID_HANDLE_VALUE) CloseHandle(hStdIn);
return false;
}
}
STARTUPINFOA si = {0};
si.cb = sizeof(si);
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdInput = redirect_input ? hStdIn : GetStdHandle(STD_INPUT_HANDLE);
si.hStdOutput = output_file.empty() ? GetStdHandle(STD_OUTPUT_HANDLE) : hStdOut;
si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
PROCESS_INFORMATION pi = {0};
// 转换命令为可修改的字符串
char* cmd_line = new char[command.size() + 1];
strcpy(cmd_line, command.c_str());
BOOL success = CreateProcessA(nullptr, cmd_line, nullptr, nullptr, TRUE,
0, nullptr, nullptr, &si, &pi);
delete[] cmd_line;
if (!success) {
DWORD err = GetLastError();
std::cerr << "CreateProcess failed: " << err << std::endl;
if (hStdIn != INVALID_HANDLE_VALUE) CloseHandle(hStdIn);
if (hStdOut != INVALID_HANDLE_VALUE) CloseHandle(hStdOut);
return false;
}
WaitForSingleObject(pi.hProcess, INFINITE);
DWORD exit_code;
GetExitCodeProcess(pi.hProcess, &exit_code);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
if (hStdIn != INVALID_HANDLE_VALUE) CloseHandle(hStdIn);
if (hStdOut != INVALID_HANDLE_VALUE) CloseHandle(hStdOut);
return exit_code == 0;
#else
// Linux/macOS: 使用 fork+exec
int input_fd = -1;
int output_fd = -1;
if (redirect_input && !input_file.empty()) {
input_fd = open(input_file.c_str(), O_RDONLY);
if (input_fd < 0) {
perror("Failed to open input file");
return false;
}
}
if (!output_file.empty()) {
output_fd = open(output_file.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (output_fd < 0) {
perror("Failed to create output file");
if (input_fd >= 0) close(input_fd);
return false;
}
}
pid_t pid = fork();
if (pid < 0) {
perror("Fork failed");
if (input_fd >= 0) close(input_fd);
if (output_fd >= 0) close(output_fd);
return false;
}
if (pid == 0) {
// 子进程
if (input_fd >= 0) {
dup2(input_fd, STDIN_FILENO);
close(input_fd);
}
if (output_fd >= 0) {
dup2(output_fd, STDOUT_FILENO);
close(output_fd);
}
// 解析命令
std::vector<char*> args;
std::string cmd_copy = command;
size_t pos = 0;
while ((pos = cmd_copy.find(' ')) != std::string::npos) {
cmd_copy[pos] = '\0';
args.push_back(&cmd_copy[0]);
cmd_copy.erase(0, pos + 1);
}
if (!cmd_copy.empty()) {
args.push_back(&cmd_copy[0]);
}
args.push_back(nullptr);
execvp(args[0], args.data());
perror("Exec failed");
exit(1);
} else {
// 父进程
int status;
waitpid(pid, &status, 0);
if (input_fd >= 0) close(input_fd);
if (output_fd >= 0) close(output_fd);
return WIFEXITED(status) && WEXITSTATUS(status) == 0;
}
#endif
}
// 查找可执行文件
std::string find_executable(const std::vector<std::string>& names) {
for (const auto& name : names) {
if (fs::exists(name)) {
// 检查是否有执行权限(非Windows)
#ifndef _WIN32
if (access(name.c_str(), X_OK) == 0) {
return name;
} else {
std::cout << "Warning: " << name << " exists but is not executable." << std::endl;
std::cout << "Trying to add execute permission..." << std::endl;
if (chmod(name.c_str(), 0755) == 0) {
std::cout << "Added execute permission to " << name << std::endl;
return name;
}
}
#else
return name;
#endif
}
}
return "";
}
// 尝试编译源文件
bool try_compile(const std::string& source, const std::string& output) {
std::cout << "Attempting to compile " << source << "..." << std::endl;
std::string compiler;
#ifdef _WIN32
// Windows: 尝试 g++, clang++, cl
std::vector<std::string> compilers = {"g++.exe", "clang++.exe", "cl.exe"};
#else
// Linux/macOS: 尝试 g++, clang++
std::vector<std::string> compilers = {"g++", "clang++"};
#endif
for (const auto& comp : compilers) {
std::string cmd = comp + " " + source + " -o " + output + " -O2 -std=c++17";
std::cout << "Trying: " << cmd << std::endl;
int result = system(cmd.c_str());
if (result == 0 && fs::exists(output)) {
std::cout << "Successfully compiled " << output << std::endl;
return true;
}
}
std::cout << "Failed to compile " << source << std::endl;
return false;
}
// 创建ZIP文件
bool create_zip(const std::string& zip_name, const std::string& dir_path) {
std::cout << "Creating ZIP archive: " << zip_name << std::endl;
#ifdef _WIN32
// Windows: 使用 PowerShell
std::string cmd = "powershell -Command \"Compress-Archive -Path '" + dir_path + "\\*' -DestinationPath '" + zip_name + "' -Force\"";
int result = system(cmd.c_str());
return result == 0;
#else
// Linux/macOS: 使用 zip 命令
std::string cmd = "cd '" + dir_path + "' && zip -r '../" + zip_name + "' .";
int result = system(cmd.c_str());
return result == 0;
#endif
}
int main() {
std::cout << "========================================\n";
std::cout << " Cross-Platform Data Generator \n";
std::cout << "========================================\n\n";
// 获取题目名称
std::string problem_name;
std::cout << "Enter problem name (English): ";
std::getline(std::cin, problem_name);
if (problem_name.empty()) {
std::cerr << "Error: Problem name cannot be empty!" << std::endl;
return 1;
}
// 获取数据组数
int test_count;
std::cout << "Enter number of test cases: ";
std::cin >> test_count;
if (test_count <= 0) {
std::cerr << "Error: Number of test cases must be positive!" << std::endl;
return 1;
}
// 查找生成器和标程
std::string gen_exe = find_executable({"gen", "gen.exe", "./gen", "./gen.exe"});
std::string std_exe = find_executable({"std", "std.exe", "./std", "./std.exe"});
// 如果找不到,尝试编译
if (gen_exe.empty()) {
if (fs::exists("gen.cpp")) {
if (try_compile("gen.cpp", "gen")) {
gen_exe = "./gen";
#ifndef _WIN32
chmod("gen", 0755);
#endif
}
}
}
if (std_exe.empty()) {
if (fs::exists("std.cpp")) {
if (try_compile("std.cpp", "std")) {
std_exe = "./std";
#ifndef _WIN32
chmod("std", 0755);
#endif
}
}
}
if (gen_exe.empty()) {
std::cerr << "Error: Cannot find or compile generator!" << std::endl;
std::cerr << "Please provide gen/gen.exe/gen.cpp" << std::endl;
return 1;
}
if (std_exe.empty()) {
std::cerr << "Error: Cannot find or compile standard solution!" << std::endl;
std::cerr << "Please provide std/std.exe/std.cpp" << std::endl;
return 1;
}
std::cout << "\nUsing generator: " << gen_exe << std::endl;
std::cout << "Using standard: " << std_exe << std::endl;
// 创建数据目录
fs::path data_dir = fs::current_path() / problem_name;
try {
fs::create_directories(data_dir);
std::cout << "Created directory: " << data_dir << std::endl;
} catch (const fs::filesystem_error& e) {
std::cerr << "Error creating directory: " << e.what() << std::endl;
return 1;
}
// 生成数据
std::atomic<int> progress(0);
std::cout << "\nGenerating test cases...\n";
std::cout << "[";
for (int i = 0; i < 50; ++i) std::cout << " ";
std::cout << "] 0%";
std::cout.flush();
auto start_time = std::chrono::high_resolution_clock::now();
for (int i = 1; i <= test_count; ++i) {
fs::path in_file = data_dir / (problem_name + std::to_string(i) + ".in");
fs::path out_file = data_dir / (problem_name + std::to_string(i) + ".out");
// 生成输入
if (!execute_command(gen_exe, "", in_file.string(), false)) {
std::cerr << "\nError generating input for test case " << i << std::endl;
return 1;
}
// 生成输出
if (!execute_command(std_exe, in_file.string(), out_file.string(), true)) {
std::cerr << "\nError generating output for test case " << i << std::endl;
return 1;
}
// 更新进度条
progress.store(i);
int percent = (i * 100) / test_count;
int bars = (percent * 50) / 100;
std::cout << "\r[";
for (int j = 0; j < bars; ++j) std::cout << "=";
for (int j = bars; j < 50; ++j) std::cout << " ";
std::cout << "] " << percent << "% (" << i << "/" << test_count << ")";
std::cout.flush();
}
auto end_time = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count();
std::cout << "\n\nAll test cases generated successfully!\n";
std::cout << "Time elapsed: " << duration << " ms\n";
// 创建ZIP文件
std::string zip_name = problem_name + ".zip";
if (create_zip(zip_name, data_dir.string())) {
std::cout << "ZIP archive created: " << zip_name << std::endl;
} else {
std::cout << "Warning: Failed to create ZIP archive.\n";
std::cout << "Data is available in: " << data_dir << std::endl;
}
std::cout << "\n========================================\n";
std::cout << " Generation Complete \n";
std::cout << "========================================\n";
std::cout << "Problem: " << problem_name << std::endl;
std::cout << "Test cases: " << test_count << std::endl;
std::cout << "Output directory: " << data_dir << std::endl;
std::cout << "Archive: " << zip_name << std::endl;
return 0;
}编译命令
也可以使用编辑器自动编译
g++ -std=c++17 -O2 datagen.cpp -o datagen.exe