Interactive + extras

  • For interactive problem [your solution and the interactor exchange the data and decide what to print based on the "history of communication"]:
    •  if you output some data it is possible that this data is first placed to some internal buffer and may be not directly transferred to the interactor => 
      • better to use endl (it flushes automatically)  after every output  
      • can also use fflush(stdout) or cout<<flush  
      • Only use with cout (NOT with cin)
    • Input/output here works much slower than in usual problems — try to use scanf/printf instead of cin/cout
    • try to find relation between number of query and number of input
      • eg.- q=(5/2)*n => for q=5 --> n=2 means using 5 queries u can find 2 elements of array
      • now make an ALGO keeping above thing in mind
  • ios_base::sync_with_stdio(false);
    • This disables the synchronization between the C and C++ standard streams. Now, printf and cout are not in sync.
    • Eg.-printf("2\n")
      cout<<"1"  --> BUT O/P = 1 2 ----> first print cout then printf
  • cin.tie(NULL);
    • unties cin from cout -> if cin and cout are tied => flushed automatically before each I/P or O/P operation on the other stream.
    • Eg.- cin.tie(NULL); cout << "Enter name:"; cin >> name;  ---> first give I/P then only the prompt to
      Enter name appears bcz cout is not flushed (stored in buffer) => output is flushed (displayed) only on demand or when the buffer is full. To avoid this, flush the cout manually every time when you want to display something before expecting input on cin.
  • Use string as char array only
  • DON'T Use
    • ios_base::sync_with_stdio(false);
      cin.tie(NULL);
      • because it might interfere with reading input and output. You won't need the speed gains anyway for interactive problems.

Comments

Popular posts from this blog

Templates (for CP)

DSA Trees + Heap

Modular Basics + Number Theory + Permutations