Interactive Problems

Interactive problems rely on the communication of two programs: one that you write the other that the problem author writes. Your program needs to interact with the problem author’s program to solve the problem described in the statement.

Here is an example of what an interactive problem would be like: https://toph.co/p/an-obvious-interactive-problem

Flushing Output

To ensure that anything your program outputs reach the driver program written by the problem author (and is not held in any internal buffer) you need to flush your output.

Every programming language has its own way of dealing with this. Below you can find some examples.

C

When using printf(), "\n" causes the output buffer to be flushed:

1
printf("Hello Toph!\n");

To force flush the output buffer, fflush() can be used on stdout:

1
2
printf("A 1520 ");
fflush(stdout);

Buffering on stdout can be disabled entirely by using setbuf():

1
setbuf(stdout, NULL);

C++

When using cout, endl causes the output buffer to be flushed:

1
cout << "Hello Toph!" << endl;

Alternatively you can use flush:

1
cout << "Hello Toph!" << flush;

If you prefer using printf in C++, you will have to use fflush() on stdout (even with newline character in the format specification):

1
2
printf("Hello Toph!\n");
fflush(stdout);

Or, disable buffering on stdout entirely using setbuf():

1
setbuf(stdout, NULL);

Python 2

You do not need to do anything extra as long as you are using print without any trailing comma.

Python 3, PyPy 3

You do not need to do anything extra as long as you are using print() without end="".

Example Solutions (of An Obvious Interactive Problem)

C++ Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>

int main() {
  setbuf(stdout, NULL);

  int L = 0, R = 1000000;
  while(true) {
    int M = (L+R)/2;
    printf("%d\n", M);

    char X[10];
    scanf("%s", X);
    if(X[2] == 'g') // Bigger
      L = M;
    else if(X[2] == 'a') // Smaller
      R = M;
    else if(X[2] == 'n') // Bingo!
      break;
  }
  return 0;
}

Python Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
L = 0
R = 1000000

while True:
    M = int((L+R)/2)
    print(M)
    
    X = input()
    if X == 'Bigger':
        L = M
    elif X == 'Smaller':
        R = M
    elif X == 'Bingo!':
        break

Search