Skip to content

Interactor

An interactor is used for interactive problems to facilitate interaction between the problem and the contestant's program. For an introduction to interactive problems, see Problem Types - Interactive Problems.

Note

Testlib only supports Codeforces-style interactive problems, i.e., interaction between two programs. It does not support NOI-style problems where contestants write functions that interact with other functions.

Please read General before proceeding.

Testlib provides a special stream std::fstream tout for interactors, which is a log stream. You can write to it in the interactor and read from it in the checker using ouf.

In an interactor, we read the problem's test data from inf, write to the standard input of the contestant's program (and the standard solution) via stdout (online), read the contestant's output from ouf (online), and read the standard output from ans (online).

If the interactor returns an ok status, the checker (if any) will take over to verify the correctness of the answer.

Usage

Windows:

1
interactor.exe <Input_File> <Output_File> [<Answer_File> [<Result_File> [-appes]]],

Linux:

1
./interactor.out <Input_File> <Output_File> [<Answer_File> [<Result_File> [-appes]]],

Simple Example

Problem

The interactor randomly selects an integer in the range \([1,10^9]\). You need to write a program to guess it. You can ask at most \(50\) times for an integer in the range \([1,10^9]\).

The interactor will return:

1: The guess is equal to the answer, and your program should stop asking.

0: The guess is smaller than the answer.

2: The guess is larger than the answer.

Note that in this problem, we do not need ans because we do not need to compare the standard output with it; however, in other problems, this may be necessary.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
int main(int argc, char** argv) {
  registerInteraction(argc, argv);
  int n = inf.readInt();  // chosen number
  cout.flush();           // flush the buffer
  int left = 50;
  bool found = false;
  while (left > 0 && !found) {
    left--;
    int a = ouf.readInt(1, 1000000000);  // query
    if (a < n)
      cout << 0 << endl;
    else if (a > n)
      cout << 2 << endl;
    else
      cout << 1 << endl, found = true;
    cout.flush();
  }
  if (!found) quitf(_wa, "couldn't guess the number with 50 questions");
  ouf.readEof();
  quitf(_ok, "guessed the number with %d questions!", 50 - left);
}

This article is mainly translated from Interactors with testlib.h - Codeforces. The GitHub repository for testlib.h is MikeMirzayanov/testlib.