Intro to competitive programming - 4

Interactive Problem

An interactive problem in competitive programming is a problem where your program interacts with a judge during execution. Your code recieves inputs, processes them and sends output step by step. We communicate with online judge using standard cout, and cin, but we need to flush the input after each cout/cin.

When you print nd output, it first goes to output buffer (the system doesnt immediately send it to he judge). If you dont flush, the judge wont recieve your output on time, and you programme will hang waiting for a reply. Inorder to avoid such situation you have to use special flush operation each time you output some data.

One simple example of this kind of problem is: there is some hidden number between 1 and 100,000. You make queries to the system, and the system returns '>', '<', or '=' in response. Below is an example of how to implement a binary search to guess the number.


    #include <iostream>
    using namespace std;

    int main() {
        int low = 1, high = 100000;

        while (low <= high) {
            int mid = (low + high) / 2;
            cout << mid << endl;
            cout.flush();  // Important to flush after each output

            string response;
            cin >> response;

            if (response == "=") {
                cout << "Found the number: " << mid << endl;
                break;
            } else if (response == ">") {
                low = mid + 1;
            } else if (response == "<") {
                high = mid - 1;
            }
        }

        return 0;
    }

To test interactive problem in your local machine, you will have to act as online judge and give input yourself.