分卷-IO交互题
ChenxinyanCxy · · 个人记录
IO 交互题
在 Codeforces、ICPC 上更常见的是 IO 交互题。参赛者的程序需要与判题系统进行交互,但交互是通过输入输出流(stdin 和 stdout)进行的。选手的程序与判题系统之间的交互是基于标准输入和输出流的读取和写入,而不是通过函数调用。
IO 交互题的配置相对简单,在文件目录下需要 checker.cpp 用作交互,以及空的 interactive_lib.cpp 用于占位。
以 P14843 [ICPC 2022 Yokohama R] Interactive Number Guessing 为例,这是一道 IO 交互题,用户输出指令(query 或者 answer,在样例输出栏),交互库读取指令后输出给用户信息(在样例输入栏的正整数)。在此类交互题中,checker 可以通过 inf 读入试题测试数据,并且从 stdin 或者 ouf 读取选手程序的输出(即 stdout)。checker 可以从 stdout 输出信息到选手程序的 stdin,允许选手程序读入。
本题的 checker 如下:
#include "testlib.h"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
static int digitsum(ll x) {
int s = 0;
while (x > 0) { s += int(x % 10); x /= 10; }
return s;
}
int main(int argc, char **argv) {
registerInteraction(argc, argv);
ll x = inf.readLong();
int query_count = 0;
while (true) {
if (ouf.seekEof()) quitf(_wa, "invalid type in query_count=%d", query_count);
string type = ouf.readToken();
if (type == "query") {
if (query_count >= 75) quitf(_wa, "query limit exceeded");
if (ouf.seekEof()) quitf(_wa, "invalid query in query_count=%d", query_count);
ll a = ouf.readLong(); // 从 ouf/stdin 读取选手程序输出
if (a < 0 || a >= 1000000000000000000LL)
quitf(_wa, "invalid range in query_count=%d: %lld", query_count, a);
cout << digitsum(a + x) << '\n'; // 从 stdout 将信息发送给选手程序,选手程序可以在 stdin 读取
cout.flush();
query_count++;
} else if (type == "answer") {
if (ouf.seekEof()) quitf(_wa, "invalid guess in query_count=%d", query_count);
ll guess = ouf.readLong();
if (guess < 0 || guess >= 1000000000000000000LL)
quitf(_wa, "invalid guess range in query_count=%d: %lld", query_count, guess);
if (guess == x) {
if (!ouf.seekEof()) quitf(_wa, "Trailing output: '%s'", ouf.readToken().c_str());
quitf(_ok, "accepted");
} else {
quitf(_wa, "wrong guess: %lld actual: %lld", guess, x);
}
} else {
quitf(_wa, "invalid type: %s", type.c_str());
}
}
}
重要注意事项
- 缓冲区问题。C/C++ 语言的输入输出函数均自带有一定的缓冲区,因此你输出的内容不一定能立刻被交互库/SPJ 所读取。如果不在合适的时间清空缓冲区,很可能会造成两个程序互相等待对方输出的情况而 TLE。
- 每次输出完一定内容、希望对面的程序开始进行处理时,都必须手动清空缓冲区。在 C 语言中,可使用
fflush(stdout)函数。在 C++ 语言中,可使用std::cout << std::flush;在使用std::endl输出一个换行时,C++ 语言也会自动清空缓冲区。 - 交互库(以及 SPJ)最好不要占用太多的 CPU 资源,因为它将与用户的程序在同一个核心上执行。最好在评测程序等待来自 SPJ 的输入,或者评测程序已经结束运行之后,再进行复杂的计算。