<|instruction|>
Solve the below problem. The solution should start with an abridged problem statement. Then key observations. Then full solution based on the observations. Then C++ and Python implementations with comments.

138. Games of Chess

time limit per test: 0.25 sec.
memory limit per test: 4096 KB


N friends gathered in order to play chess, according to the following rules. In the first game, two of the N friends will play. In the second game, the winner of the first game will play against another friend (maybe even the same friend who lost the first game). In the third game, the winner of the second game will play against someone else and so on.. No game will end as a draw (tie). Given the number of games each of the N friends played, find a schedule for the games, so that the above rules are obeyed.


Input

The first line contains the number of friends N (2<=N<=100). The second line contains N integers, separated by blanks, representing the number of games each friend played. The first number represents the number of games played by the first friend, the second number represents the number of games played by the second friend and so on..


Output

The first line should contain the number of games played by all the friends (it will be an integer between 1 and 10 000, for every test case). Let's suppose this number is G. Then, G lines follow, each of them containing two integers, describing the games. The first line contains the numbers of the two friends who played the first game. The friend printed first is considered to be the winner. Each of the next G-1 lines contain the integers a and b, where a<>b and a or b is the winner of the previous game. The friend printed first on the line is considered to be the winner of the game.
It is guaranteed that for every test case there will be at least one possible scheduling of the games.


Sample Input

4
2 4 1 5
Sample Output

6
4 3
4 1
2 4
2 1
4 2
2 4
Author	: Mugurel Ionut Andreica
Resource	: SSU::Online Contester Fall Contest #2
Date	: Fall 2002

<|response|>
1. Abridged Problem Statement  
You have N players, each of whom must appear in exactly a[i] games (as winner or loser). You need to arrange a sequence of G = (∑a[i])⁄2 chess games so that:  
- In game 1, any two players meet.  
- In each subsequent game, one of the players is the winner of the previous game.  
- No game is drawn.  
Output any valid sequence of G games (winner, loser) satisfying the above and the per-player appearance counts.

2. Key Observations  
- The total number of games G = (∑a[i])⁄2 must be integer and it is guaranteed a solution exists.  
- We need to build a chain of games: the “current champion” (winner of the last game) must play in the next game.  
- If the champion has more than one game remaining, it’s safe to let him win again (we consume one of his required games but keep him champion).  
- If the champion has exactly one game left, he cannot win (or he’d have zero games left but still need to hand off), so we force him to lose to someone else who still needs games, passing the champion role.  
- Games where the champion wins can initially record only the winner, and we fill in losers later from the pool of players with remaining required games.

3. Full Solution Approach  
1. Read N and array a[1..N]. Compute sum = ∑a[i], G = sum/2.  
2. Create a permutation perm of players sorted in descending order of a[i]. Build array b[0..N–1] where b[k] = a[perm[k]]. Index 0 is the initial “champion.”  
3. Phase 1 (Decide winners & placeholders):  
   - Initialize an empty list matches. Let p = 0 (current champion position in b).  
   - Repeat G times:  
     a. If b[p] > 1, record a match (winner = p, loser = –1 placeholder), decrement b[p].  
     b. Else (b[p] == 1), record match (winner = p+1, loser = p), decrement b[p] and b[p+1], then set p = p+1 (new champion).  
4. Phase 2 (Assign actual losers):  
   - Maintain pointer q = 0. Scan matches in order; whenever a match has loser == –1, advance q until b[q] > 0, set that match’s loser = q, and decrement b[q].  
5. Output G, then for each match (w_idx, l_idx), print “perm[w_idx]+1 perm[l_idx]+1” on its own line.  

This constructs a valid chain: in Phase 1 every next game involves the champion, and in Phase 2 we ensure every player reaches its required total appearances.

4. C++ Implementation with Detailed Comments  
```cpp
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int N;
    cin >> N;
    vector<int> a(N);
    for (int i = 0; i < N; i++) {
        cin >> a[i];
    }

    // Total games = sum(a) / 2
    int sum = accumulate(a.begin(), a.end(), 0);
    int G = sum / 2;

    // Build permutation of players sorted by descending appearances
    vector<int> perm(N);
    iota(perm.begin(), perm.end(), 0);
    sort(perm.begin(), perm.end(), [&](int i, int j){
        return a[i] > a[j];
    });

    // b[k] = remaining needed appearances of player perm[k]
    vector<int> b(N);
    for (int k = 0; k < N; k++) {
        b[k] = a[perm[k]];
    }

    // matches: pairs (winner_index_in_b, loser_index_in_b or -1)
    vector<pair<int,int>> matches;
    matches.reserve(G);

    int p = 0;  // current champion position in b[]

    // Phase 1: decide winners; losers = -1 means placeholder
    for (int i = 0; i < G; i++) {
        if (b[p] > 1) {
            // Champion wins again, postpone picking the actual opponent
            matches.emplace_back(p, -1);
            b[p]--;
        } else {
            // Champion has exactly one game left: force him to lose
            // to the next player, handing off the champion role
            matches.emplace_back(p+1, p);
            b[p]--;
            b[p+1]--;
            p = p + 1;  // new champion
        }
    }

    // Phase 2: fill in losers for placeholder matches
    int q = 0;  // pointer to find any player with b[q] > 0
    for (auto &mv : matches) {
        if (mv.second == -1) {
            // find next available player
            while (b[q] == 0) q++;
            mv.second = q;
            b[q]--;
        }
    }

    // Output result: translate back to original 1-based labels
    cout << G << "\n";
    for (auto &mv : matches) {
        int w = perm[mv.first] + 1;
        int l = perm[mv.second] + 1;
        cout << w << " " << l << "\n";
    }
    return 0;
}
```

5. Python Implementation with Detailed Comments  
```python
import sys

def main():
    data = sys.stdin.read().split()
    N = int(data[0])
    a = list(map(int, data[1:]))

    total = sum(a)
    G = total // 2

    # Sort players descending by required appearances
    perm = list(range(N))
    perm.sort(key=lambda i: -a[i])

    # b[k] = remaining appearances of player perm[k]
    b = [a[i] for i in perm]

    # matches: list of [winner_idx, loser_idx] where loser_idx=-1 means placeholder
    matches = []
    p = 0  # current champion position in b

    # Phase 1: decide winners and placeholders
    for _ in range(G):
        if b[p] > 1:
            # champion wins, postpone opponent
            matches.append([p, -1])
            b[p] -= 1
        else:
            # champion must lose to pass on token
            matches.append([p+1, p])
            b[p]   -= 1
            b[p+1] -= 1
            p += 1  # new champion

    # Phase 2: assign actual losers to placeholder matches
    q = 0
    for mv in matches:
        if mv[1] == -1:
            while b[q] == 0:
                q += 1
            mv[1] = q
            b[q] -= 1

    # Output, mapping back to original labels (1-based)
    out = [str(G)]
    for w, l in matches:
        out.append(f"{perm[w]+1} {perm[l]+1}")
    sys.stdout.write("\n".join(out))

if __name__ == "__main__":
    main()
```