Two flows share a link

Two TCP flows share a bottleneck that can carry C segments per round trip. Both use AIMD. Watch them move toward a fair share.

What to build

A program that simulates two AIMD flows for k rounds.

Requirements

  • Round 1 starts with windows w1 and w2. Print w1 w2 for the start of each of k rounds.
  • After each round: if the windows add up to more than C, both flows see a loss and each window becomes half of itself (rounded down), but at least 1. Otherwise each window grows by 1.
  • After the k lines print difference D, where D is the absolute difference of the windows at the start of round k.

Input

One line: C, k, w1 and w2.

Output

k lines of two numbers, then the difference line.

Constraints

2 ≤ C ≤ 200; 1 ≤ k ≤ 60; 1 ≤ w1, w2 ≤ 200.

Example

Input:

20 10 1 15

Output:

1 15
2 16
3 17
4 18
2 9
3 10
4 11
5 12
6 13
7 14
difference 7

Why it works

Adding 1 keeps the difference between the flows, but halving cuts it in half. After many losses the difference shrinks towards 0, which is why AIMD converges to equal shares.

Examples

Example 1 · Input
20 10 1 15
Expected output
1 15
2 16
3 17
4 18
2 9
3 10
4 11
5 12
6 13
7 14
difference 7
Example 2 · Input
10 5 3 3
Expected output
3 3
4 4
5 5
6 6
3 3
difference 0

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Print the windows at the start of each round, before updating them.

Hint 2

If w1 + w2 is more than the capacity C, both flows lose a packet: each window becomes max(1, w // 2). Otherwise each adds 1.

Hint 3

The difference of the two windows is halved at every loss and unchanged by additive increase.

Solution

Show one correct solution (try it yourself first)
c, k, w1, w2 = map(int, input().split())
last = (w1, w2)
for _ in range(k):
    last = (w1, w2)
    print(w1, w2)
    if w1 + w2 > c:
        w1 = max(1, w1 // 2)
        w2 = max(1, w2 // 2)
    else:
        w1 += 1
        w2 += 1
print("difference", abs(last[0] - last[1]))

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: TCP congestion control →