Chapter 1

Home

Reading Input and Writing Output

Before you can solve any problem, you need to talk to the automated judge. Every competitive programming problem works the same way: your program reads from stdin and writes to stdout.

The Pipeline

The automated judge sends input to your program's standard input stream. Your program processes it and prints the result to standard output. The judge program compares your output character-by-character against the expected answer.

stdin Your Program stdout Automated judge compares your output against expected answer

The A+B Problem

Every competitive programmer starts here. Given two integers a and b, print their sum. Simple — but it teaches you the I/O pattern you'll use in every single solution.

C++

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int a, b;
    cin >> a >> b;
    cout << a + b << "\n";
    return 0;
}

Rust

use std::io::{self, Read};

fn main() {
    let mut input = String::new();
    io::stdin().lock().read_to_string(&mut input).unwrap();
    let mut nums = input
        .split_whitespace()
        .map(|x| x.parse::<i64>().unwrap());
    let a = nums.next().unwrap();
    let b = nums.next().unwrap();
    println!("{}", a + b);
}

💡 Why read().split()?

Reading all input at once then splitting is faster than reading one token at a time. For competitive programming, this matters when input is large — it's fewer system calls. You'll use this pattern in almost every solution.

📐 Try it

Create a file input.txt containing 3 7. Compile and run with ./solution < input.txt. It should print 10.

Multiple Test Cases

Most problems don't give you just one test case — they give you T test cases. The first line of input tells you how many. Your program loops through each one, printing one answer per line.

📋 Sample input

3
1 2
10 20
100 200

Expected output

3
30
300

C++

#include <bits/stdc++.h>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t; cin >> t;
    while (t--) {
        int a, b; cin >> a >> b;
        cout << a + b << "\n";
    }
    return 0;
}

Rust

use std::io::{self, Read};
fn main() {
    let stdin = io::stdin();
    let mut input = String::new();
    stdin.lock().read_to_string(&mut input).unwrap();
    let nums: Vec<i64> = input
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();
    let t = nums[0] as usize;
    for i in 0..t {
        let a = nums[1 + i * 2];
        let b = nums[2 + i * 2];
        println!("{}", a + b);
    }
}

Key Takeaways

Practice

Solve these to lock in the pattern: